(Rails) Reloading “lib” files without having to re

2019-01-23 02:51发布

问题:

This question already has an answer here:

  • How do I make the code in lib/ automatically reload when the file changes? 4 answers

Is there any way in Rails to have the ENV reload "lib" files without having to restart the server? I'm working with some classes that I have inside a module in "lib". However, in order to see my changes I must restart the server each time. I'm guessing this is the way Rails is intended to work, but it is quite tedious when developing library files and/or plugins.

Surely I'm going about this wrong....?

Best

EDIT 1

Neither answer 1 nor 2 worked for me. Instead I was presented with errors from the controllers that made use of the Module. FYI, I have 3 files in my "lib/xmlitems" directory. I attempted to load that subdirectory then I referenced the single file that "requires" all other files. Am I to individually load all files?

回答1:

For Rails 3 and Rails 4.0, vary the instructions given in @txwikinger's answer. In your environments/development.rb file, add the lines:

ActiveSupport::Dependencies.autoload_paths << File::join( Rails.root, 'lib')
ActiveSupport::Dependencies.explicitly_unloadable_constants << '<my modules in lib>'


回答2:

module ActsAsReloadable
  def self.included(base)
    ActiveSupport::Dependencies.explicitly_unloadable_constants << base.name if Rails.env == 'development'
  end
end

To use it, simply include ActsAsReloadable in your lib/* files and add config.autoload_paths += %W(#{config.root}/lib) in config/application.rb



回答3:

There's an easier way: just add

config.reload_plugins = true

to development.rb