Monday 23 February 2015

ActiveAdmin simple_table

ActiveAdmin by default will build you a table (using table_for) for a collection of objects. But sometimes you just want to throw up a quick table of random values - eg on a dashboard you want a table where the left=column is a description and the right column is, say sets of counts of various things.

ActiveAdmin uses Arbre under the covers to build html for you This means you can use it to laboriously build an html table using all the tags. But if you just want to throw together a super-simple table, this means too much typing.

So I've written a convenience method that will take an array of values and convert it directly to a table.

Note: it does no checking... so make sure your array has the same number of columns for each row

# put this in config/initializers/active_admin.rb
module ActiveAdmin
  module Views
    class SimpleTable < Arbre::HTML::Table
      builder_method :simple_table

      def build(collection)
        table do
         collection.each do |row|
           tr do
             row.each do |col|
               if col.is_a? Numeric
                 td col, style: "text-align: right;"
               else
                 td col
               end
             end
           end
         end
        end
      end
    end
  end
end


# example usage
simple_table [ [ "User count", User.count ],
               [ "Item count", Item.count ],
               [ "Total Wishes", Wish.count ],
               [ "Available Items", Item.available.count ] ]