Class: Hirb::Helpers::ActiveRecordTable

Inherits:
ObjectTable show all
Defined in:
lib/hirb/helpers/active_record_table.rb

Constant Summary

Constants inherited from Table

Table::BORDER_LENGTH

Class Method Summary collapse

Methods inherited from Table

#adjust_long_fields, #array_to_indices_hash, #default_field_lengths, #default_restrict_field_lengths, #filter_values, #format_cell, #initialize, #render, #render_border, #render_footer, #render_header, #render_rows, #render_table_description, #render_table_header, #restrict_field_lengths, #set_fields, #setup_field_lengths, #setup_rows, #validate_values

Constructor Details

This class inherits a constructor from Hirb::Helpers::Table

Class Method Details

.query_used_select?(rows) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


23
24
25
# File 'lib/hirb/helpers/active_record_table.rb', line 23

def self.query_used_select?(rows) #:nodoc:
  rows.first.attributes.keys.sort != rows.first.class.column_names.sort
end

.render(rows, options = {}) ⇒ Object

Rows are Rails’ ActiveRecord::Base objects. Takes same options as Hirb::Helpers::Table.render except as noted below.

Options:

:fields- Can be any attribute, column or not. If not given, this defaults to the database table's columns.


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/hirb/helpers/active_record_table.rb', line 7

def self.render(rows, options={})
  rows = [rows] unless rows.is_a?(Array)
  options[:fields] ||= 
    begin
      fields = rows.first.class.column_names
      fields.map {|e| e.to_sym }
    end
  if query_used_select?(rows)
    selected_columns = rows.first.attributes.keys
    sorted_columns = rows.first.class.column_names.dup.delete_if {|e| !selected_columns.include?(e) }
    sorted_columns += (selected_columns - sorted_columns)
    options[:fields] = sorted_columns.map {|e| e.to_sym}
  end
  super(rows, options)
end