ruby-on-rails 主动管理关注动态方法

vm0i2vca  于 2023-02-10  发布在  Ruby
关注(0)|答案(2)|浏览(170)

我有一个活跃的管理资源。我如何可以动态扩展资源。我尝试这样做:

ActiveAdmin.register Order do
  include UpdatePriceBlock
  price_blocks_names names: [:last, :actual]

end
module UpdatePriceBlock
  extend ActiveSupport::Concern

  def price_blocks_names(options = {})
    @price_blocks_names ||= options[:names]
  end

  def self.included(base)
    @price_blocks_names.each do |name|
      base.send :member_action, name,  method: :get do
      end
    end
  end
end

现在我有一个错误:

undefined method `price_blocks_names' for #<ActiveAdmin::ResourceDSL
ztyzrc3y

ztyzrc3y1#

这是一种可行的方法,我还不知道如何将名称保存在活动的管理寄存器块中。将price_blocks_names添加到您的模型中:

class Order < ApplicationRecord
  def self.price_bloks_names
    %i(last actual)
  end
end

然后将其放入config/initializers/active_admin_update_price_block.rb

module ActiveAdminUpdatePriceBlock
  def self.extended(base)
    base.instance_eval do
      self.controller.resource_class.price_bloks_names.each do |name|
        member_action name, method: :get do
          raise resource.inspect
        end
      end 
    end
  end 
end

现在你可以扩展了,但是配置需要以类方法的形式驻留在模型中,到目前为止还没有找到更干净的方法。

ActiveAdmin.register Order do
  extend UpdatePriceBlock
end
rdlzhqv9

rdlzhqv92#

我想我找到了

ActiveAdmin.register Order do
  controller do
    include UpdatePriceBlock
  end
end

发生了什么事:
register Order do块中,self是一个特殊的活动管理功能:

ActiveAdmin.register Order do
  puts "What's self here? #{self}"
end

=〉What's self here? #<ActiveAdmin::ResourceDSL:0x000000012b948230>
controller do块中,它是控制器类(因此,与类定义的主体几乎相同):

ActiveAdmin.register Order do
  controller do
    puts "What's self here? #{self}"
    include UpdatePriceBlock
  end
end

=〉What's self here? Admin::OrdersController
member_action块中,它是控制器的一个示例,就像在常规Rails控制器操作中一样:

ActiveAdmin.register Order do
  member_action :action do
    puts "What's self here? #{self}"
  end
end

=〉What's self here? #<Admin::OrdersController:0x00000001259e7e80>

相关问题