Sha256: 1934118892a4231bbd830c49d4325143c995573493d31c27f025a76d13b48972

Contents?: true

Size: 1.03 KB

Versions: 2

Compression:

Stored size: 1.03 KB

Contents

class Hirb::Helpers::ActiveRecordTable < Hirb::Helpers::ObjectTable
  # Rows are Rails' ActiveRecord::Base objects. These objects should all be from one class.
  # 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.
  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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hirb-0.2.9 lib/hirb/helpers/active_record_table.rb
hirb-0.2.8 lib/hirb/helpers/active_record_table.rb