Class: BlockMapper

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

Overview

A generic mapping class for “collections” bm = BlockMapper.new bm.before_each {|rec,index| # do something here like: rec.extend(MyMethods) } bm.map :indexer, ‘Matt’ bm.map :id do |rec,index|

  rec[:id]

end

mapped_data = bm.run(my_collection_of_somethings)

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (BlockMapper) initialize

A new instance of BlockMapper



18
19
20
# File 'lib/block_mapper.rb', line 18

def initialize
  @mappings = []
end

Instance Attribute Details

- (Object) after_each_mapped_value_blk (readonly)

Returns the value of attribute after_each_mapped_value_blk



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

def after_each_mapped_value_blk
  @after_each_mapped_value_blk
end

- (Object) before_each_source_item_blk (readonly)

Returns the value of attribute before_each_source_item_blk



15
16
17
# File 'lib/block_mapper.rb', line 15

def before_each_source_item_blk
  @before_each_source_item_blk
end

- (Object) mappings (readonly)

Returns the value of attribute mappings



14
15
16
# File 'lib/block_mapper.rb', line 14

def mappings
  @mappings
end

Instance Method Details

- (Object) after_each_mapped_value(&blk)



31
32
33
# File 'lib/block_mapper.rb', line 31

def after_each_mapped_value(&blk)
  @after_each_mapped_value_blk=blk
end

- (Object) before_each_source_item(&blk)



27
28
29
# File 'lib/block_mapper.rb', line 27

def before_each_source_item(&blk)
  @before_each_source_item_blk = blk
end

- (Object) map(output_field_name, value = nil, &blk)



22
23
24
25
# File 'lib/block_mapper.rb', line 22

def map(output_field_name, value=nil, &blk)
  raise 'Can provide a value (second arg) or a block, not both' if value and block_given?
  @mappings << {:field_name=>output_field_name, :value=>value, :blk=>blk}
end

- (Object) run(collection, &blk)



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/block_mapper.rb', line 35

def run(collection, &blk)
  docs=[]
  collection.each_with_index do |rec,index|
    @before_each_source_item_blk.call(rec,index) if @before_each_source_item_blk
    doc={}
    @mappings.each do |m|
      field = m[:field_name]
      value = m[:blk] ? m[:blk].call(rec, index) : m[:value].to_s
      value = @after_each_mapped_value_blk.call(field, value) if @after_each_mapped_value_blk
      doc[field] = value
    end
    yield(doc, index) if block_given?
    docs << doc
  end
  docs
end