Skip to content

Instantly share code, notes, and snippets.

@eiwi1101
Last active June 12, 2024 20:00
Show Gist options
  • Save eiwi1101/1e32562c7369d87e5681 to your computer and use it in GitHub Desktop.
Save eiwi1101/1e32562c7369d87e5681 to your computer and use it in GitHub Desktop.
A table helper file for HAML templates that allows you to make tables of a data collection painfully easy.
%h1 All Users
- table_for User.all do
- column "Username" => :username
- column "Email" => ->(m) { mail_to m.email }
- column "Notes" => :notes
module TableHelper
# Creates a table based on a model by building the required columns.
# Could be extended further to support Pagination, that's a homework assignment.
#
# Accepts a block which includes the #column method. To this method, you pass the
# string for the column heading, and a symbol or lambda (with one parameter) for
# the table data.
#
# Currently a HAML helper.
#
# @example
# - table_for User.new do
# - column "Username" => :username
# - column "Email" => ->(m) { mail_to m.email }
# - column "Notes" => :notes
#
def table_for(model, &columns)
column_hash = TableColumns.new(&columns).to_h
haml_tag :table do
haml_tag :thead do
haml_tag :tr do
column_hash.keys.each do |th|
haml_tag :th, th
end
end
end
haml_tag :tbody do
model.each do |m|
haml_tag :tr do
column_hash.values.each do |td|
val = if td.kind_of?(Symbol)
m.send(td)
else
td.call(m)
end
haml_tag :td, val
end
end
end
end
end
end
# Helper class for the TableHelper to parse the block provided
# into a column hash.
#
# Extend this to provide other data processing options, other than
# the default #column method.
#
class TableColumns
include Rails.application.routes.url_helpers
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
def initialize(&block)
@cols = Hash.new
self.instance_eval(&block)
end
def column(*args)
if args.first.kind_of? Hash
@cols[args.first.keys.first] = args.first.values.first
else
@cols[args[0]] = args[1]
end
end
def to_h
@cols
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment