Rails Engines: Helpers only are reloaded when restarting the server

强颜欢笑 提交于 2019-12-10 01:31:50

问题


I'm currently experimenting with moving functionality into engines. It works nicely so far, but I'm a bit confused why certain parts of the engine are always automatically reloaded when something changed, and some are not.

Specifically, when adding a helper method, I have to restart the Rails server, otherwise it is not seen by Rails. Is this normal behavior? Here's the relevant part of my engine:

components/iq_list.rb

# encoding: utf-8
require 'iq_list/engine'

# Load IqList Modules
module IqList
  extend ActiveSupport::Autoload
  autoload :Helpers
  autoload :Models
  autoload :Controllers
end

components/iq_list/engine.rb

module IqList
  class Engine < ::Rails::Engine
  end
end

components/iq_list/helpers.rb

module IqList
  module Helpers
    extend ActiveSupport::Autoload
    autoload :IqListHelper
  end
end

components/iq_list/helpers/iq_list_helper.rb

module IqList
  module Helpers
    module IqListHelper
      def some_method
        # ...
      end
    end
  end
end

I'm still very new to engines, and a lot of the code above I have taken from somebody else's work, so please be patient with me. Any hint into the right direction is highly appreciated.


回答1:


It appears that you may be barking up the wrong tree with Engines. If you're trying to simply achieve separation of concerns, you probably just want to make some plain old ruby classes and stick them in lib/ (in an organized way of course).

An Engine would be developed separately from your 'current' project at likely brought in through a gem. Changes in included gems would necessitate restarting your server AFAIK.




回答2:


If you need code from your engine reloaded on every request you need to place it in the to_prepare block of the engines intialization code

module IqList
  class Engine < ::Rails::Engine
    config.to_prepare do
     ApplicationController.helper(IqListHelper)
    end
  end
end

Code in the to_prepare block is guaranteed to run once in production and every time in development.

see the rails guides as well as What does this Rails Engine code mean: config.to_prepare &method(:activate).to_proc

and

http://robots.thoughtbot.com/tips-for-writing-your-own-rails-engine



来源:https://stackoverflow.com/questions/12191822/rails-engines-helpers-only-are-reloaded-when-restarting-the-server

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