Module: Tablesmith::HashRowsBase
- Included in:
- ActiveRecordSource, HashRowsSource
- Defined in:
- lib/tablesmith/hash_rows_base.rb
Overview
ActiveRecord and HashRowsSource share a lot, but not everything.
Instance Method Summary collapse
- #create_headers(rows) ⇒ Object
-
#normalize_keys(rows) ⇒ Object
not all resulting rows will have data in all columns, so make sure all rows pad out missing columns.
- #row_values(row) ⇒ Object
- #sort_columns(rows) ⇒ Object
Instance Method Details
#create_headers(rows) ⇒ Object
31 32 33 34 |
# File 'lib/tablesmith/hash_rows_base.rb', line 31 def create_headers(rows) column_names = rows.first.map(&:first) grouped_headers(column_names) + [apply_column_aliases(column_names), :separator] end |
#normalize_keys(rows) ⇒ Object
not all resulting rows will have data in all columns, so make sure all rows pad out missing columns
4 5 6 7 |
# File 'lib/tablesmith/hash_rows_base.rb', line 4 def normalize_keys(rows) all_keys = rows.map(&:keys).flatten.uniq rows.map { |hash_row| all_keys.each { |key| hash_row[key] ||= '' } } end |
#row_values(row) ⇒ Object
27 28 29 |
# File 'lib/tablesmith/hash_rows_base.rb', line 27 def row_values(row) row.map(&:last) end |
#sort_columns(rows) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/tablesmith/hash_rows_base.rb', line 9 def sort_columns(rows) return if column_order.empty? rows.map! do |row| # this sort gives preference to column_order then falls back to alphabetic for leftovers. # this is handy when columns auto-generate based on hash data. row.sort do |a, b| a_col_name, b_col_name = [a.first, b.first] a_col_index, b_col_index = [column_order.index(a_col_name), column_order.index(b_col_name)] if a_col_index.nil? && b_col_index.nil? a_col_name <=> b_col_name else (a_col_index || 999) <=> (b_col_index || 999) end end end end |