Class: CsvMapper::AttributeMap

Inherits:
Object
  • Object
show all
Defined in:
lib/csv-mapper/attribute_map.rb

Overview

A CsvMapper::AttributeMap contains the instructions to parse a value from a CSV row and to know the name of the attribute it is targeting.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, index, map_context) ⇒ AttributeMap

Creates a new instance using the provided attribute name, CSV row index, and evaluation map_context



8
9
10
# File 'lib/csv-mapper/attribute_map.rb', line 8

def initialize(name, index, map_context)
  @name, @index, @map_context = name, index, map_context
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



5
6
7
# File 'lib/csv-mapper/attribute_map.rb', line 5

def index
  @index
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/csv-mapper/attribute_map.rb', line 5

def name
  @name
end

Instance Method Details

#at(index) ⇒ Object

Set the index that this map is targeting.

Returns this AttributeMap for chainability



19
20
21
22
# File 'lib/csv-mapper/attribute_map.rb', line 19

def at(index)
  @index = index
  self
end

#map(transform = nil, &block_transform) ⇒ Object

Provide a lambda or the symbol name of a method on this map’s evaluation context to be used when parsing the value from a CSV row.

Both the lambda or the method provided should accept a single row parameter

Returns this AttributeMap for chainability



29
30
31
32
# File 'lib/csv-mapper/attribute_map.rb', line 29

def map(transform=nil, &block_transform)
  @transformer = block_transform || transform
  self
end

#parse(csv_row) ⇒ Object

Given a CSV row, return the value at this AttributeMap’s index using any provided map transforms (see map)



35
36
37
# File 'lib/csv-mapper/attribute_map.rb', line 35

def parse(csv_row)
  @transformer ? parse_transform(csv_row) : raw_value(csv_row)
end

#raw_value(csv_row) ⇒ Object

Access the raw value of the CSV row without any map transforms applied.



40
41
42
# File 'lib/csv-mapper/attribute_map.rb', line 40

def raw_value(csv_row)
  csv_row[self.index]
end

#to_sObject



12
13
14
# File 'lib/csv-mapper/attribute_map.rb', line 12

def to_s
  "#{@index}: #{@name}"
end