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

12,841

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.

Share:
12,841

Related videos on Youtube

corbin
Author by

corbin

Updated on October 05, 2022

Comments

  • corbin
    corbin over 1 year

    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!

  • Steven Aguilar
    Steven Aguilar over 5 years
    wheres that answer?
  • nachbar
    nachbar over 5 years
    @StevenAguilar - it is at stackoverflow.com/questions/1068558/…