Class: Bumblebee::Column

Inherits:
Object
  • Object
show all
Defined in:
lib/bumblebee/column.rb

Overview

This is main piece of logic that defines a column which can go from objects to csv cell values and csv rows to objects.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field:, header: nil, to_csv: nil, to_object: nil) ⇒ Column

Returns a new instance of Column.

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
28
# File 'lib/bumblebee/column.rb', line 21

def initialize(field:, header: nil, to_csv: nil, to_object: nil)
  raise ArgumentError, 'field is required' unless field

  @field      = field
  @header     = make_header(header || field)
  @to_csv     = Array(to_csv || field)
  @to_object  = Array(to_object || @header)
end

Instance Attribute Details

#field ⇒ Object (readonly)

Returns the value of attribute field.



16
17
18
# File 'lib/bumblebee/column.rb', line 16

def field
  @field
end

#header ⇒ Object (readonly)

Returns the value of attribute header.



16
17
18
# File 'lib/bumblebee/column.rb', line 16

def header
  @header
end

#to_csv ⇒ Object (readonly)

Returns the value of attribute to_csv.



16
17
18
# File 'lib/bumblebee/column.rb', line 16

def to_csv
  @to_csv
end

#to_object ⇒ Object (readonly)

Returns the value of attribute to_object.



16
17
18
# File 'lib/bumblebee/column.rb', line 16

def to_object
  @to_object
end

Instance Method Details

#csv_to_object(csv_hash) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/bumblebee/column.rb', line 45

def csv_to_object(csv_hash)
  return nil unless csv_hash

  value = csv_hash

  to_object.each do |f|
    value = single_extract(value, f)
  end

  hash = {}
  hash.tap { hash[field] = value }
end

#object_to_csv(object) ⇒ Object

Take a object and convert to a value.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bumblebee/column.rb', line 31

def object_to_csv(object)
  val = object

  # Iterate over keys until we reach a nil or the end of keys.
  to_csv.each do |f|
    # short-circuit out of the extract method
    return nil unless val

    val = single_extract(val, f)
  end

  val
end