Class: Bumblebee::Template

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(columns = []) ⇒ Template

Returns a new instance of Template.



17
18
19
# File 'lib/bumblebee/template.rb', line 17

def initialize(columns = [])
  @columns = ::Bumblebee::Column.array(columns)
end

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, options = {})
  objects = objects.is_a?(Hash) ? [objects] : Array(objects)

  write_options = options.merge(headers: headers, write_headers: true)

  CSV.generate(write_options) 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, options = {})
  csv = CSV.new(string, options.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