Extending controllers of a Rails 3 Engine in the m

2020-01-27 02:53发布

I am using a Rails engine as a gem in my app. The engine has PostsController with a number of methods and I would like to extend the controller logic in my main app, e.g. to add some methods. If I just create PostsController in the main app, then the engine's controller is not loaded.

There is a solution proposed in question Rails engines extending functionality based on altering ActiveSupport::Dependencies#require_or_load

Is it the only/correct way to do this? If yes, where do I put that piece of code?

EDIT1:

This is the code suggested by Andrius for Rails 2.x

module ActiveSupport::Dependencies
  alias_method :require_or_load_without_multiple, :require_or_load
  def require_or_load(file_name, const_path = nil)
    if file_name.starts_with?(RAILS_ROOT + '/app')
      relative_name = file_name.gsub(RAILS_ROOT, '')
      @engine_paths ||= Rails::Initializer.new(Rails.configuration).plugin_loader.engines.collect {|plugin| plugin.directory }
      @engine_paths.each do |path|
        engine_file = File.join(path, relative_name)
        require_or_load_without_multiple(engine_file, const_path) if File.file?(engine_file)
      end
    end
    require_or_load_without_multiple(file_name, const_path)
  end
end

7条回答
疯言疯语
2楼-- · 2020-01-27 03:33

Why not just inherit from the Engine's controller class in your application (and point your routes at the new child controllers)? Sounds conceptually similar to the way that you extend built-in Devise controllers.

查看更多
登录 后发表回答