Class: Bumblebee::Template
- Inherits:
-
Object
- Object
- Bumblebee::Template
- Defined in:
- lib/bumblebee/template.rb
Overview
Wraps up columns and provides to main methods: generate_csv: take in an array of objects and return a string (CSV contents) parse_csv: take in a string and return an array of OpenStruct objects
Instance Attribute Summary collapse
-
#columns ⇒ Object
readonly
Returns the value of attribute columns.
Instance Method Summary collapse
- #generate_csv(objects, options = {}) ⇒ Object
-
#headers ⇒ Object
Return array of strings (headers).
-
#initialize(columns = []) ⇒ Template
constructor
A new instance of Template.
- #parse_csv(string, options = {}) ⇒ Object
Constructor Details
Instance Attribute Details
#columns ⇒ Object (readonly)
Returns the value of attribute columns.
15 16 17 |
# File 'lib/bumblebee/template.rb', line 15 def columns @columns end |
Instance Method Details
#generate_csv(objects, options = {}) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/bumblebee/template.rb', line 26 def generate_csv(objects, = {}) objects = objects.is_a?(Hash) ? [objects] : Array(objects) = .merge(headers: headers, write_headers: true) CSV.generate() do |csv| objects.each do |object| row = columns.map { |column| column.object_to_csv(object) } csv << row end end end |
#headers ⇒ Object
Return array of strings (headers)
22 23 24 |
# File 'lib/bumblebee/template.rb', line 22 def headers columns.map(&:header) end |
#parse_csv(string, options = {}) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/bumblebee/template.rb', line 40 def parse_csv(string, = {}) csv = CSV.new(string, .merge(headers: true)) # Drop the first record, it is the header record csv.to_a.map do |row| # Build up a hash using the column one at a time extracted_hash = columns.inject({}) do |hash, column| hash.merge(column.csv_to_object(row)) end extracted_hash end end |