I'm trying to create a helper method to DRY up my views a lot, that would essentially render out a table for me. The syntax I'm looking to use so far is:
= table_for @notes do
= column "Date" do
= time_ago(note.created_at)
= column "Content" do
= note.content
This is the helper that I have so far:
module TableHelper
def table_for(items)
@resource = items.singularize # Singularizes the resource
@columns = []
yield
# Create a table
content_tag :table, class: 'table table-striped' do
thead + tbody(items)
end
end
def thead # Loop through columns and print column label
content_tag :thead do
content_tag :tr do
@columns.each do |c|
concat(content_tag(:th, c[:label]))
end
end
end
end
def tbody(items) # This bit fails :(
content_tag :tbody do
items.each { |e|
concat(content_tag(:tr){
@columns.each { |c|
e[c[:label]] = c[:block].call(e[c[:label]]) if c[:block]
concat(content_tag(:td, e[c[:block]]))
}
})
}
end
end
def column (label, &block) # Takes a label and block, appending it to the columns instance
@columns << { label: label, block: block}
nil # Stops it printing the @columns variable
end
end
Where this falls short is in the tbody method. I have no idea how I would pass in the singular resource to the block.
For example in this case I'm passing @notes in as a collection. In the column block, I then call note.created_at. However, 'note' is not defined.
Any help would be greatly appreciated!