Class: Bumblebee::Template
- Inherits:
-
Object
- Object
- Bumblebee::Template
- Extended by:
- ColumnDsl, Forwardable
- 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 hashes
Instance Attribute Summary collapse
-
#object_class ⇒ Object
readonly
Returns the value of attribute object_class.
Instance Method Summary collapse
- #column(header, opts = {}) ⇒ Object
- #generate(objects, options = {}) ⇒ Object
-
#initialize(columns: nil, object_class: Hash, &block) ⇒ Template
constructor
A new instance of Template.
- #parse(string, options = {}) ⇒ Object
Methods included from ColumnDsl
Constructor Details
#initialize(columns: nil, object_class: Hash, &block) ⇒ Template
Returns a new instance of Template.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/bumblebee/template.rb', line 22 def initialize(columns: nil, object_class: Hash, &block) @column_set = ::Bumblebee::ColumnSet.new(self.class.all_columns) @object_class = object_class column_set.add(columns) return unless block_given? if block.arity == 1 yield self else instance_eval(&block) end end |
Instance Attribute Details
#object_class ⇒ Object (readonly)
Returns the value of attribute object_class.
20 21 22 |
# File 'lib/bumblebee/template.rb', line 20 def object_class @object_class end |
Instance Method Details
#column(header, opts = {}) ⇒ Object
37 38 39 40 41 |
# File 'lib/bumblebee/template.rb', line 37 def column(header, opts = {}) column_set.column(header, opts) self end |
#generate(objects, options = {}) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/bumblebee/template.rb', line 43 def generate(objects, = {}) objects = objects.is_a?(Hash) ? [objects] : Array(objects) = .merge(headers: headers, write_headers: true) CSV.generate() do |csv| objects.each do |object| csv << columns.each_with_object({}) do |column, hash| column.csv_set(object, hash) end end end end |
#parse(string, options = {}) ⇒ Object
57 58 59 60 61 62 63 64 65 66 |
# File 'lib/bumblebee/template.rb', line 57 def parse(string, = {}) csv = CSV.new(string, .merge(headers: true)) csv.to_a.map do |row| # Build up a hash using the column one at a time columns.each_with_object(object_class.new) do |column, object| column.object_set(row, object) end end end |