4

I have a bunch of custom classes in my Rails 3.2 app in lib folder: i.e. extending ActiveRecord, etc. It all works fine.

However I'm trying to add a couple of custom methods to FileUtils, i.e.

module FileUtils
  def last_modified_file(path='.')
     # blah ...    
  end
end

I put it in lib/file_utils.rb In my application.rb I have

config.autoload_paths += %W(#{config.root}/lib)

My other custom classed are loaded but not the module.

I read (Best way to load module/class from lib folder in Rails 3? ) that I'm supposed to define a class inside module in order for Rails to pick it up and according to FileUtils.class - it should be Object < BasicObject.

So I tried

module FileUtils
  class Object 
    def last_modified_file(path='.')
       # blah ...    
    end
  end
end

But that doesn't work either.

However when I fire up irb and just paste my code which effectivly puts my new code inside object and reinclude my module - it works fine.

Whaat amd I missing here?

Community
  • 1
  • 1
konung
  • 6,908
  • 6
  • 54
  • 79

1 Answers1

14

Your patch is never going to be loaded because autoload is only invoked when Rails can't find a constant. Since the FileUtils constant already exists, the autoloader is never called, and your file is never loaded.

Simply require it from an initializer.

require File.join(Rails.root, "lib/file_utils.rb")
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • That's what I'm doing right now. I have an initializer `require_libs.rb` for some of the gems that need to be specifically required. `require "#{Rails.root}/lib/file_utils.rb"; include FileUtils ` . So you are saying there is not another Rails "automagic" way of doing it? – konung Nov 02 '12 at 20:51
  • 4
    Correct. Autoloading only works for constants that are not yet present. When a missing constant is encountered, Rails searches the autoload paths for a file matching the snake_cased version of the constant name and loads it. – Chris Heald Nov 02 '12 at 21:10