Active Admin refactoring

195 views Asked by At

I am currently creating a dashboard in Active Admin for my product orders (and associated models). I want to show data from multiple models within this table, and as a result the table is horribly repetitive. I am not very good with Active Admin and would love some advice on refactoring this code:

#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

To give you more information about my models and associations, there is an Order model which has_many order_items and has_one customer_info. order_items and customer_info both belong to Order.

1

There are 1 answers

0
Andrey Deineko On BEST ANSWER

I don't think there is a need for refactoring - what you have is readable and understandable code. But, if you still want to, you could use, for example, some metaprogramming.

For instance, this piece of code:

  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

can become this short:

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