开发者

What is the best way to load files from the lib folder that add methods to ~existing~ classes in Rails 3?

开发者 https://www.devze.com 2023-03-01 13:45 出处:网络
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.

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 开发者_Go百科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 }
0

精彩评论

暂无评论...
验证码 换一张
取 消