在主应用程序中扩展Rails 3引擎的控制器 [英] Extending controllers of a Rails 3 Engine in the main app

查看:95
本文介绍了在主应用程序中扩展Rails 3引擎的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用Rails引擎作为宝石。该引擎具有 PostsController 以及许多方法,我想扩展主应用程序中的控制器逻辑,例如添加一些方法。如果我在主应用程序中创建 PostsController ,那么引擎的控制器不会被加载。

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.

提出了 Rails引擎扩展功能,基于改变 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:

这是由Andrius建议 for Rails 2.x

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


推荐答案

为什么不从应用程序中的引擎的控制器类继承(并将您的路由指向新的子控制器)?听起来在概念上与扩展内置Devise控制器的方式类似。

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.

这篇关于在主应用程序中扩展Rails 3引擎的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆