3

I am using config.autoload_paths in a way very similar to this related question to load classes from the lib directory in a Rails 3 project.

Specifically, I've added these lines to the config/application.rb file:

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

However, this method is not working for me for existing classes. When I add a file like lib/extensions/string.rb:

class String
  def foo
    puts "foo"
  end
end

I get an undefined method 'foo' for "":Stringerror. Through various searches I've got the sense that this problem has to do with the lazy loading of these files. I tried using config.eager_load_paths but was not able to get that to work.

Community
  • 1
  • 1
Rick
  • 810
  • 7
  • 10

1 Answers1

1

I'm doing exactly what you are describing in my application, and the only difference is that I also have an initializer called extensions.rb with the following code:

Dir.glob('lib/extensions/*').each { |f| require f }
Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • 1
    This initializer method works for me. However, I had to change it slightly to this: `Dir.glob("#{Rails.root}/lib/extensions/*").each { |f| require f }` Do you agree? – Rick Apr 30 '11 at 23:20
  • Also, there is a nice example of autoload vs. require referenced in another question in this [blog post](http://ablogaboutcode.com/2011/01/17/ruby-autoloading-explained/) – Rick Apr 30 '11 at 23:24
  • Using the full path is probably better, but wasn't needed for my application. Not sure why that would be though. – Peter Brown May 01 '11 at 01:38
  • You ought to use eager_load_paths for thread safety and automatic reloaded classes on changes, as posted here http://blog.plataformatec.com.br/2012/08/eager-loading-for-greater-good/ – Ricardo de Cillo May 09 '13 at 18:52