0

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!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ammar
  • 1,091
  • 12
  • 23
  • I didnt understand the line `@resource = items.singularize` in `table_for` method. Aren't you calling `singularize` method on `Array`. And it should not work I guess. Would please explain a bit more? – Samiron Sep 04 '12 at 10:05
  • Your absolutely correct, that's not meant to be in there! That was from a previous attempt, but if you have any suggestions on how to make this work that would be great! :) – Ammar Sep 06 '12 at 12:37
  • Are you trying something modified than the one you posted in your question. If yes, pls update your question, otherwise ive updated my answer with a link you can try with. Apart from this I will take a look on this in weekend. – Samiron Sep 07 '12 at 03:21

1 Answers1

0

Probably you need to replace

= table_for @notes do` 

by

= table_for @notes do |note|

from the table_for function when you are yielding you should do yield item. Here item is one instance of the items array. So need to prepare that also.

EDIT: This link has a different approach: https://stackoverflow.com/a/11483295/1160106

Community
  • 1
  • 1
Samiron
  • 5,169
  • 2
  • 28
  • 55