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

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

问题描述

我在我的应用程序中使用 Rails 引擎作为 gem.引擎有 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

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?

编辑 1:

这是 Andrius 建议的代码,用于 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

推荐答案

为什么不直接从应用程序中的 Engine 控制器类继承(并将路由指向新的子控制器)?听起来在概念上类似于您扩展内置设计控制器的方式.

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天全站免登陆