Active Admin重构

时间:2015-06-07 20:51:34

标签: ruby-on-rails activeadmin

我目前正在Active Admin中为我的产品订单(及相关型号)创建一个仪表板。我想在此表中显示来自多个模型的数据,因此该表非常重复。我对Active Admin不太满意,并且非常喜欢重构这段代码的建议:

#dashboard.rb

section "Your tasks for this week" do
    table_for Order.all do
        column "Order ID",     :id
        column "Status" do |order|
            order.order_status.name
        end
        column "Email" do |order|
            order.customer_info.email
        end
        column "Name" do |order|
            order.customer_info.name
        end
        column "Address" do |order|
            order.customer_info.address
        end
        column "City" do |order|
            order.customer_info.city
        end
        column "State/Province" do |order|
            order.customer_info.province
        end
        column "Postal Code" do |order|
            order.customer_info.postal
        end
        column "Country" do |order|
            order.customer_info.country
        end
        column "Bagel" do |order|
            order.order_items.each do |oi|
                li oi.bagel_type
            end
        end
        column "Topping1" do |order|
            order.order_items.each do |oi|
                li oi.topping1
            end
        end
        column "Topping2" do |order|
            order.order_items.each do |oi|
                li oi.topping2
            end
        end
        column "Topping3" do |order|
            order.order_items.each do |oi|
                li oi.topping3
            end
        end
        column "Open" do |order|
            order.order_items.each do |oi|
                li oi.open
            end
        end
    end
end

为了向您提供有关我的模型和关联的更多信息,我们有一个Order模型has_many order_itemshas_one customer_infoorder_itemscustomer_info都属于Order

1 个答案:

答案 0 :(得分:2)

我认为不需要重构 - 您拥有的是可读且易于理解的代码。 但是,如果你仍然想要,你可以使用,例如,一些元编程。

例如,这段代码:

  column "Email" do |order|
    order.customer_info.email
  end
  column "Name" do |order|
    order.customer_info.name
  end
  column "Address" do |order|
    order.customer_info.address
  end
  column "City" do |order|
    order.customer_info.city
  end

可以变成这么简短:

  %w(Email Name Address City).each do |title|
    column title do |order|
      order.customer_info.send("#{title.downcase}")
    end
  end