Class: Rehash::Mapper

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, opts = Rehash.default_options) ⇒ Mapper

Returns a new instance of Mapper.



5
6
7
8
9
10
# File 'lib/rehash/mapper.rb', line 5

def initialize(source, opts = Rehash.default_options)
  @source = source
  @result = {}
  @symbolize_keys = opts[:symbolize_keys]
  @delimiter = opts[:delimiter]
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



3
4
5
# File 'lib/rehash/mapper.rb', line 3

def result
  @result
end

Instance Method Details

#[](path) ⇒ Object



25
26
27
# File 'lib/rehash/mapper.rb', line 25

def [](path)
  get_value(path)
end

#[]=(path, value) ⇒ Object



29
30
31
# File 'lib/rehash/mapper.rb', line 29

def []=(path, value)
  put_value(path, value)
end

#call(mapping, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rehash/mapper.rb', line 12

def call(mapping, &block)
  default = mapping.delete(:default) if mapping.key?(:default)

  mapping.each do |from, to|
    value = get_value(from)
    value = default if value.nil? && !default.nil?
    value = yield value if block_given?
    put_value(to, value)
  end

  result
end

#map_array(mapping) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/rehash/mapper.rb', line 33

def map_array(mapping)
  call(mapping) do |value|
    value.map do |item|
      Rehash.map(item) do |item_re|
        yield item_re
      end
    end
  end
end

#map_hash(mapping) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rehash/mapper.rb', line 43

def map_hash(mapping)
  call(mapping) do |value|
    Rehash.map(value) do |nested_re|
      yield nested_re
    end
  end
end