Class: Antz::FieldMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/antz/field_mapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ FieldMapper

Returns a new instance of FieldMapper.



5
6
7
8
# File 'lib/antz/field_mapper.rb', line 5

def initialize(&block)
  @mappings = {}
  instance_eval(&block) if block
end

Instance Method Details

#map(source_key, to: nil, &transform) ⇒ Object Also known as: field



10
11
12
13
# File 'lib/antz/field_mapper.rb', line 10

def map(source_key, to: nil, &transform)
  target_key = to || source_key
  @mappings[source_key] = { target: target_key, transform: transform }
end

#transform(row) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/antz/field_mapper.rb', line 17

def transform(row)
  result = {}
  @mappings.each do |src, opts|
    value = row[src.to_s] || row[src.to_sym]
    value = opts[:transform].call(value) if opts[:transform]
    result[opts[:target]] = value
  end
  result
end