Module: EasyMapper

Defined in:
lib/EasyMapper.rb,
lib/EasyMapper/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#afterObject

Returns the value of attribute after.



2
3
4
# File 'lib/EasyMapper.rb', line 2

def after
  @after
end

#outputObject

Returns the value of attribute output.



2
3
4
# File 'lib/EasyMapper.rb', line 2

def output
  @output
end

#target_mapObject

Returns the value of attribute target_map.



2
3
4
# File 'lib/EasyMapper.rb', line 2

def target_map
  @target_map
end

Class Method Details

.extended(base) ⇒ Object



4
5
6
7
8
# File 'lib/EasyMapper.rb', line 4

def self.extended(base)
  base.class_eval do
    self.target_map = nil
  end
end

Instance Method Details

#after_normalize(&block) ⇒ Object



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

def after_normalize(&block)
  self.after = block
end

#find_input_value(obj, key) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/EasyMapper.rb', line 46

def find_input_value(obj, key)
  return recurse_dig(key.split('#'), obj) if key.split('#').count > 1
  if obj.respond_to?(:key?) && obj.key?(key)
    obj[key]
  elsif obj.respond_to?(:each)
    r = nil
    obj.find{ |*a| r = find_input_value(a.last, key) }
    r
  end
end

#handle_array(input, target_map, key, output) ⇒ Object



42
43
44
# File 'lib/EasyMapper.rb', line 42

def handle_array(input, target_map, key, output)
  output[key] = input.map {|i| normalize_hash(target_map, i)}
end

#map(input_map) ⇒ Object



10
11
12
# File 'lib/EasyMapper.rb', line 10

def map(input_map)
  self.target_map = input_map
end

#normalize(input_hash) ⇒ Object



18
19
20
21
22
# File 'lib/EasyMapper.rb', line 18

def normalize(input_hash)
  output = normalize_hash(self.target_map, input_hash)
  output = after.call(input_hash, output) if after
  output
end

#normalize_hash(target_map, input, buried_keys = [], output = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/EasyMapper.rb', line 24

def normalize_hash(target_map, input, buried_keys = [], output = {})
  target_map.keys.each do |key|
    if key.include?('*')
      keys = key.split('*')
      handle_array(input[keys[1]], target_map[key], keys[0], output)
    else
      buried_keys.push(key)
      if target_map[key].is_a?(Hash)
        normalize_hash(target_map[key], input, buried_keys, output)
      else
        output.bury(buried_keys, find_input_value(input, target_map[key]))
      end
      buried_keys = []
    end
  end
  output
end

#recurse_dig(keys, obj) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/EasyMapper.rb', line 57

def recurse_dig(keys, obj)
  if keys.count > 1
    key = keys.shift
    recurse_dig(keys, obj.dig(key))
  else
    return obj.dig(keys.shift)
  end
end