Class: Tabler::CSV
- Inherits:
-
Object
- Object
- Tabler::CSV
- Defined in:
- lib/tabler/csv.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Instance Method Summary collapse
-
#generate(opts = {}) ⇒ Object
(also: #to_csv, #to_s)
Create a csv string from the data.
-
#initialize(data) ⇒ CSV
constructor
A new instance of CSV.
-
#normalized_data ⇒ Object
Creates a hash with a :headers field and a :values field.
Constructor Details
#initialize(data) ⇒ CSV
Returns a new instance of CSV.
7 8 9 |
# File 'lib/tabler/csv.rb', line 7 def initialize(data) @data = data end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
5 6 7 |
# File 'lib/tabler/csv.rb', line 5 def data @data end |
Instance Method Details
#generate(opts = {}) ⇒ Object Also known as: to_csv, to_s
Create a csv string from the data
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/tabler/csv.rb', line 13 def generate(opts={}) nd = normalized_data ::CSV.generate(opts) do |csv| # set header row csv << nd[:headers] nd[:values].each do |row| csv << row end end end |
#normalized_data ⇒ Object
Creates a hash with a :headers field and a :values field
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/tabler/csv.rb', line 30 def normalized_data result = { :headers => [], :values => [] } data.each do |row| values = [] row.each do |key,val| # add the header field if needed result[:headers] << key unless result[:headers].include?(key) # build the values array index_of_header = result[:headers].index(key) values[index_of_header] = val end result[:values] << values end result end |