Skip to content

Instantly share code, notes, and snippets.

@GuyPaddock
Last active November 22, 2017 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuyPaddock/769b97b52179112321b27be3ae4527f7 to your computer and use it in GitHub Desktop.
Save GuyPaddock/769b97b52179112321b27be3ae4527f7 to your computer and use it in GitHub Desktop.
Enhanced Simple Table for ActiveAdmin + Arbre
module ActiveAdmin
module Views
##
# Exposes Arbre's table support as a simple control for use in ActiveAdmin.
#
# Example usage:
# ```
# simple_table [ [ "User count", User.count ],
# [ "Item count", Item.count ],
# [ "Total Wishes", Wish.count ],
# [ "Available Items", Item.available.count ] ]
# ```
#
# Based on the following source (released into the public domain):
# http://rubyglasses.blogspot.com.br/2015/02/activeadmin-simpletable.html
#
class SimpleTable < ::Arbre::HTML::Table
builder_method :simple_table
def build(collection)
ensure_uniform_columns(collection)
collection.each do |row|
tr do
row.each do |col|
td col, style: style_for(col)
end
end
end
end
##
# Ensures that this control renders as a table.
#
# (This prevents the default Arbre behavior of trying to render a
# "<simpletable>" tag instead).
def tag_name
'table'
end
private
##
# Ensures every row within the given two-dimensional array has the same
# number of columns.
#
# @param [Array<Array<Object>>]
# A two-dimensional array of values, in which the first dimension is
# rows, and the second dimension is columns.
#
def ensure_uniform_columns(values)
return if values.empty?
distinct_column_lengths = values.map(&:length).uniq
unless distinct_column_lengths.length == 1
raise ArgumentError,
"Not all columns are the same length (got column lengths of "\
"#{distinct_column_lengths})."
end
end
##
# Obtains the appropriate inline style for the specified column value.
#
# @param [Object] col
# The value being displayed in the column.
#
def style_for(col)
if col.is_a? Numeric
'text-align: right;'
else
''
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment