简体   繁体   English

如何在我的gem中扩展ApplicationController?

[英]How to extend ApplicationController in my gem?

For example, I want to stop render layout for all actions. 例如,我要停止所有动作的渲染布局。 I can write in ApplicationController this code and its work: 我可以在ApplicationController中编写此代码及其工作:

layout :false

So, I want to create gem, which add this functionality. 因此,我想创建添加此功能的gem。 I try this code in lib of my gem: 我在我的gem的lib中尝试以下代码:

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

  class ApplicationLayoutController < ApplicationController
    layout :false
  end
end

and this: 和这个:

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

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

But it is not working. 但这是行不通的。 How can I do it? 我该怎么做?

You are just defining your own ApplicationController class. 您只是在定义自己的ApplicationController类。 It lives in your module, like so: MyLayout::ApplicationController . 它位于您的模块中,如下所示: MyLayout::ApplicationController It doesn't affect the app that uses them gem by just existing. 它不会影响仅使用现有宝石的应用程序。

If you want to provide the wanted functionality for users of your gem, you have a couple of options. 如果要为gem用户提供所需的功能,则有两种选择。

The "nicest" is probably to provide your own subclass of ActionController::Base and instruct your users to inherit from that: “最有趣的”可能是提供您自己的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

Another way is to provide a module, which runs layout: false when included: 另一种方法是提供一个运行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

Another way, but probably not very advisable, is to monkey patch ActionController::Base . 另一种方法,但可能不是很明智,是猴子修补ActionController::Base

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

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