简体   繁体   中英

What is the best way to load files from the lib folder that add methods to ~existing~ classes in Rails 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 "":String error. 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.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM