无法为关注点定义多个“包含”块

问题描述 投票:0回答:1

我正在使用 ActiveAdmin,为了模块化我的代码,我尝试将 Active Admin 成员操作包装在关注范围内

module Example
  extend ActiveSupport::Concern
  included do

    def func
      member_action :history, method: :get do
       # some_code_here
      end
    end

  end
end

在我的 ActiveAdmin 中我写道

ActiveAdmin.register Post do
  include Example

我收到此错误,知道为什么吗?

ruby-on-rails activeadmin activesupport activesupport-concern
1个回答
0
投票

你在这里做/问的事情根本没有意义。

ActiveSupport::Concern#included
是围绕
Module#included
挂钩的方便包装。

所以你所做的只是:

module Example
  extend ActiveSupport::Concern

  def self.included(othermod)
    def func
      member_action :history, method: :get do
       # some_code_here
      end
    end
  end
end

在方法内部使用

def
是非常不受欢迎的,因为它将在外部作用域中定义该方法,并且每次调用该方法时都会重新定义该方法。如果您真的想做元编程,请使用
define_method

模块中也不能包含多个包含的块,因为

ActiveSupport::Concern#included
会引发:

def included(base = nil, &block)
  if base.nil?
    if instance_variable_defined?(:@_included_block)
      if @_included_block.source_location != block.source_location
        raise MultipleIncludedBlocks
      end
    else
      @_included_block = block
    end
  else
    super
  end
end

如果您希望将方法作为实例方法添加到包含类中,请勿将其包装到包含块中:

module Example
  def func
    member_action :history, method: :get do
      # some_code_here
    end
  end
end

或者根本不将对宏方法的调用包装在方法中:

module Example
  extend ActiveSupport::Concern

  included do
    member_action :history, method: :get do
      # some_code_here
    end
  end
end

如果你想添加类方法,你可以使用class_methods

© www.soinside.com 2019 - 2024. All rights reserved.