【问题标题】:Extend ActionController::Base from a Rails 4 engine从 Rails 4 引擎扩展 ActionController::Base
【发布时间】:2014-11-13 17:25:14
【问题描述】:

我正在尝试从 rails 4 引擎扩展 ActionController::Base,以便安装它的任何应用程序在每个操作之前运行特定方法。现在我知道可能有几种不同的方法可以做到这一点,比如关注、class_eval 或开放分类,但我对这一切都很陌生,我能找到的链接主要是关于如何从主控制器扩展引擎控制器应用程序,而不是像我想要的那样。

这是我尝试过的,我在引擎的控制器文件夹中创建了一个新文件夹,如下所示:

my_engine
  |-- app
        |-- controllers
              |-- action_controller
                  |-- base_controller.rb
              |-- my_engine
                  |-- some_controller.rb
                  |-- other_controller.rb

base_controller.rb 中,我添加了以下内容:

require_dependency "action_controller/base"

module ActionController
  class BaseController

    before_action :some_method

    private
    def some_method
      #just for testing
      redirect_to 'http://www.google.com'
    end
  end
end

这不起作用。我认为这是因为它没有被加载(我仍在试图了解如何以及在哪里将这样的自定义代码放置在 rails 引擎中),所以我尝试将该代码复制到 my_engine/lib/my_engine/engine.rb 文件但后来我得到了启动服务器时出现以下错误:

undefined method `before_action' for ActionController::BaseController:Class (NoMethodError)

如何做到这一点,我应该将文件正确放置在哪里?

【问题讨论】:

    标签: ruby-on-rails ruby rails-engines activesupport-concern


    【解决方案1】:

    可以在引擎Engine 类中轻松实现,例如:

    class Engine < ::Rails::Engine
    
      ActionController::Base.class_eval do
    
         include Some::Module
    
      end
    
    end
    

    然而,这种方法意味着Some::Module 中的任何更改都需要重新启动服务器才能加载该更改。这可能很烦人,所以也许使用简单的 OOP 继承会更好地解决这个问题。

    在这种情况下,引擎将为某些控制器提供逻辑,我们称之为EngineController。现在,控制器层次结构如下所示:

    class EngineController < ActionController::Base; end # provided with an engine
    class MainAppController < EngineController; end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2011-01-20
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2011-03-28
      相关资源
      最近更新 更多