Rails3 not reloading code in lib while in development mode

淺唱寂寞╮ 提交于 2019-11-27 20:12:52

问题


THE SITUATION:

  1. I have code in lib/foo/bar.rb with a simple method defined as such:

    module Foo
      class Bar
        def test
          "FooBar"
        end
      end
    end
    
  2. In my helper, FooBarHelper, I have:

    require `lib/foo/bar`
    module FooBarHelper
      def test_foo_bar
        fb = Foo::Bar.new
        fb.test
      end
    end
    
  3. In my view, I call this helper method like so:

    <%= test_foo_bar =>
    
  4. In my config/environments/development.rb, I added the directory to my config.autoload_paths:

    config.autoload_paths += ["#{config.root}/lib/foo"]
    

THE PROBLEM:

When I change the return value of Foo::Bar.test to, for example, "MODIFIED FOOBAR", the original return value, "FooBar", is still being displayed on the view and not the new value.

Since I'm in development mode, shouldn't the code reload the code on every request?

Could someone tell me what I'm missing?

Thanks!


回答1:


They removed the lib folder the app root in Rails 3.

You can either add it back
config.autoload_paths << 'lib'
or you can use `require_dependency` in your helper.
module FooBarHelper
  require_dependency 'foo/bar'

  def test_foo_bar
    fb = Foo::Bar.new
    fb.test
  end
end

Both ways tell Rails that your file lib/foo/bar.rb should be autoloaded and subsequently, reloaded each request.




回答2:


Previous answers does not work. Here is a working one: http://ileitch.github.com/2012/03/24/rails-32-code-reloading-from-lib.html

You have to use both:

config.watchable_dirs['lib'] = [:rb]

and

require_dependency

but any config.autoload_paths based solution won't work in Rails ~> 3.2




回答3:


Autoloading code from the lib folder was intentionally disabled in rails3, see this ticket for more details.

The workaround suggested by Samuel is a great start, however I found that certain environments still had difficulty finding the libraries in a testing environment (say being invoked from a cucumber scenario), and that including the root path, as suggested within the ticket and hinted by the original comment in application.rb was a more robust approach:

config.autoload_paths += %W(#{config.root}/lib)



回答4:


Why are you putting the require into the module, when using autoload_path you should not need to require the file at all, it should be working without, I think if you manually require the file afterwards, rails does not know when to load it again?

Something like this:

require `bar`

module FooBarHelper

  def test_foo_bar
    fb = Foo::Bar.new
    fb.test
  end

end

should work, no need for having the require inside your module.



来源:https://stackoverflow.com/questions/4018757/rails3-not-reloading-code-in-lib-while-in-development-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!