8

I'd like to create a general purpose string manipulation class that can be used across Models, Views, and Controllers in my Rails application.

Right now, I'm attempting to put a Module in my lib directory and I'm just trying to access the function in rails console to test it. I've tried a lot of the techniques from similar questions, but I can't get it to work.

In my lib/filenames.rb file:

module Filenames

  def sanitize_filename(filename)
    # Replace any non-letter or non-number character with a space
    filename.gsub!(/[^A-Za-z0-9]+/, ' ')

    #remove spaces from beginning and end
    filename.strip!

    #replaces spaces with hyphens
    filename.gsub!(/\ +/, '-')
  end

  module_function :sanitize_filename

end

When I try to call sanitize_filename("some string"), I get a no method error. When I try to call Filenames.sanitize_filename("some string"), I get an uninitilized constant error. And when I try to include '/lib/filenames' I get a load error.

  1. Is this the most conventional way to create a method that I can access anywhere? Should I create a class instead?

  2. How can I get it working? :)

Thanks!

4

1 回答 1

13

要获得一个非常好的答案,请查看对您的问题的评论中引用的 Yehuda Katz 的回答(真的,一定要看看)。

在这种情况下,简短的回答是您可能没有加载文件。请参阅 RyanWilcox 给您的链接。您可以通过在文件中放置语法错误来检查这一点 - 如果在启动应用程序(服务器或控制台)时未引发语法错误,您就知道文件没有被加载。

如果您认为您正在加载它,请发布您用于加载它的代码。再次,请参阅 RyanWilcox 为您提供的链接以了解详细信息。它包含此代码,该代码将进入您的环境配置文件之一:

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

但实际上,请阅读耶胡达的回答。

于 2013-08-23T03:09:25.257 回答