Guest User

Untitled

a guest
Mar 17th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. module TableHelper
  2. # Table helper allow easy generate simple table layout
  3. # items - collection of variables
  4. # options:
  5. # you can define any attribute for table in this parameter
  6. # ex. :style => 'border: 1px solid black', :align => 'center'
  7. # You can ovveride predefined next parameters:
  8. # cols: count of columns in a table
  9. # rows: count of rows in a table. The cols parameter will be disabled in this case.
  10. # tr: options for a tr tag, ex.: :tr => {:class => 'block', :width => '100px'}
  11. # td: options for a td tag. You can assign false on td parameter, it's mean helper will not generate td tags, only tr.
  12. # Examples of use:
  13. # <% table @genres, :cols => 3, :td => {:width => '200px'} do |genre| -%>
  14. # <i><%= genre.name %></i>
  15. # <% end %>
  16. #
  17. # <% table @genres, :td => false do |genre| -%>
  18. # <td><%= genre.id %></td>
  19. # <td><%= genre.name %></td>
  20. # <% end %>
  21. def table(items, options, &block)
  22. cols = options[:cols] || 1
  23. cols = items.size / options[:rows].to_i if options[:rows]
  24. tr_options = options[:tr]
  25. td_options = options[:td]
  26. options[:cols] = nil
  27. options[:rows] = nil
  28. options[:tr] = nil
  29. options[:td] = nil
  30.  
  31. if td_options != false
  32. trs = ""
  33. items.each_slice(cols) do |slice|
  34. # generate td tags for current tr tag
  35. tds = slice.inject("") do |tds, item|
  36. tds + content_tag(:td, capture(item, &block), td_options)
  37. end
  38.  
  39. trs += content_tag(:tr, tds, tr_options)
  40. end
  41. else
  42. trs = items.inject(""){|trs, item| trs + content_tag(:tr, capture(item, &block), tr_options) }
  43. end
  44.  
  45. # send generated table to view
  46. concat(content_tag(:table, trs, options))
  47. end
  48. end
Add Comment
Please, Sign In to add comment