Module: EasyTable::ViewExt::Table::Data

Defined in:
lib/easy-table/table/data_table.rb

Instance Method Summary collapse

Instance Method Details

#data_table(collection, headers, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/easy-table/table/data_table.rb', line 3

def data_table(collection, headers, options = {})    
  obj_type = get_obj_type collection
  set_options! options

  return options[:placeholder] unless collection.any?

  # try to extract attributes from headers!
  attributes = options[:attributes] || extract_attributes(collection.first, headers)

  arg_err = "You must specify an :attributes hash option to indicate which attributes of #{obj_type.camelize} should be rendered in the table!"
  raise ArgumentError, arg_err if !attributes.any?

  rows_options = options.delete(:rows) || {}

  options.delete :placeholder
  caption = options.delete :caption
  footer  = options.delete :footer

 
  render_table options do
    [
      render_caption(caption),
      render_header(headers),
      render_footer(footer, headers),
      indent_tag(1, :tbody) do
        data_rows(collection, attributes, rows_options).indent 1
      end
    ].compact.join
  end
end

#extract_attributes(obj, headers) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/easy-table/table/data_table.rb', line 34

def extract_attributes obj, headers
  headers.map do |header|
    att = header.to_s.underscore
    attrib = obj.send att
    att ? att : nil
  end.compact
end

#get_obj_type(collection) ⇒ Object



52
53
54
# File 'lib/easy-table/table/data_table.rb', line 52

def get_obj_type collection
  collection.first.class.to_s      
end

#set_options!(options = {}, obj_type = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/easy-table/table/data_table.rb', line 42

def set_options! options={}, obj_type=nil
  options.reverse_merge!({
    :placeholder  => 'Nothing to display',
    :caption      => nil,
    :summary      => nil,
    :footer       => '',
    :class        => obj_type
  })           
end