繁体   English   中英

如何在我的gem中扩展ApplicationController?

[英]How to extend ApplicationController in my gem?

例如,我要停止所有动作的渲染布局。 我可以在ApplicationController中编写此代码及其工作:

layout :false

因此,我想创建添加此功能的gem。 我在我的gem的lib中尝试以下代码:

module MyLayout
  class Engine < ::Rails::Engine
  end

  class ApplicationLayoutController < ApplicationController
    layout :false
  end
end

和这个:

module MyLayout
  class Engine < ::Rails::Engine
  end

  class ApplicationController < ActionController::Base
    layout :false
  end
end

但这是行不通的。 我该怎么做?

您只是在定义自己的ApplicationController类。 它位于您的模块中,如下所示: MyLayout::ApplicationController 它不会影响仅使用现有宝石的应用程序。

如果要为gem用户提供所需的功能,则有两种选择。

“最有趣的”可能是提供您自己的ActionController::Base的子类,并指示您的用户从中继承:

module MyLayout
  class Engine < ::Rails::Engine
  end

  class ApplicationLayoutController < ApplicationController
    layout :false
  end
end

# When using your gem

class MyController < MyLayout::ApplicationLayoutController
  # stuff
end

另一种方法是提供一个运行layout: false的模块layout: false如果包含,则返回layout: false

module MyLayout
  class Engine < ::Rails::Engine
  end

  module MyLayoutController
    def self.included(base)
      base.layout(:false)
    end
  end
end

# When using your gem

class MyController < ApplicationController
  include MyLayoutController
end

另一种方法,但可能不是很明智,是猴子修补ActionController::Base

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM