Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Can't access a module in my lib directory

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!

like image 349
corbin Avatar asked Aug 23 '13 00:08

corbin


Video Answer


1 Answers

For a really great answer, look at Yehuda Katz' answer referenced in the comment to your question (and really, do look at that).

The short answer in this case is that you probably are not loading your file. See the link that RyanWilcox gave you. You can check this by putting a syntax error in your file - if the syntax error is not raised when starting your app (server or console), you know the file is not being loaded.

If you think you are loading it, please post the code you are using to load it. Again, see the link RyanWilcox gave you for details. It includes this code, which goes into one of your environment config files:

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

But really, read Yehuda's answer.

like image 126
nachbar Avatar answered Sep 20 '22 18:09

nachbar