Rails: unable to access module in my lib directory

I would like to create a general-purpose string manipulation class that can be used in models, views, and controllers in my Rails application.

I'm currently trying to put a module in my lib directory, and I'm just trying to access a function in the rails console to test it. I tried many methods 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 method error. When I try to call Filenames.sanitize_filename ("some string"), I get an uninitialized persistent error. And when I try to include '/ lib / filenames', I get a loading error.

  • Is this the most common way to create a method with which I can access anywhere? Should I create a class instead?

  • How can I make it work? :)

Thanks!

+7
ruby ruby-on-rails ruby-on-rails-3
source share
1 answer

For a really great answer, look at Yehuda Katz's answer mentioned in the commentary on your question (and really, look at that).

The short answer in this case is that you probably are not downloading the file. See the Link provided by RyanWilcox. You can verify this by placing a syntax error in your file - if a syntax error does not occur when your application (server or console) starts, you know that the file is not loading.

If you think you are downloading it, send the code that you use to download it. Again, see the link that RyanWilcox gave you for details. It includes this code, which is included in one of your environment configuration files:

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

But actually, read the answer of Yehuda.

+10
source share

All Articles