相关疑难解决方法(0)

在主应用程序中扩展Rails 3引擎的控制器

我在我的应用程序中使用Rails引擎作为gem.引擎有PostsController很多方法,我想在我的主应用程序中扩展控制器逻辑,例如添加一些方法.如果我只是PostsController在主应用程序中创建,则不会加载引擎的控制器.

有一个解决方案提出了Rails引擎基于改变扩展功能ActiveSupport::Dependencies#require_or_load

这是唯一/正确的方法吗?如果是的话,我在哪里放这段代码?

EDIT1:

这是Andrius为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
Run Code Online (Sandbox Code Playgroud)

rubygems ruby-on-rails rails-engines ruby-on-rails-3

15
推荐指数
2
解决办法
9704
查看次数