Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails doesn't load my module from lib

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?

like image 644
konung Avatar asked Oct 16 '25 20:10

konung


1 Answers

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")
like image 111
Chris Heald Avatar answered Oct 18 '25 11:10

Chris Heald