class Jibe::HashMapper

Attributes

key_map[R]
value_map[R]

Public Class Methods

new(key_map, value_map) click to toggle source
# File lib/jibe/hash_mapper.rb, line 10
def initialize(key_map, value_map)
  @key_map = key_map
  @value_map = value_map
end

Public Instance Methods

map(attributes) click to toggle source
# File lib/jibe/hash_mapper.rb, line 15
def map(attributes)
  map_values(map_keys(attributes, key_map), value_map)
end

Protected Instance Methods

map_keys(attributes, key_map) click to toggle source
# File lib/jibe/hash_mapper.rb, line 20
def map_keys(attributes, key_map)
  key_map = key_map.dup.symbolize_keys!
  transformation =  t(:symbolize_keys) >> t(:accept_keys, key_map.keys) >> t(:rename_keys, key_map)
  transformation.call attributes
end
map_values(attributes, value_map) click to toggle source
# File lib/jibe/hash_mapper.rb, line 26
def map_values(attributes, value_map)
  attributes.each do |key, value|
    value_mapping = value_map[key]
    if value_mapping && value_mapping.kind_of?(String)
      attributes[key] = value_mapping
    elsif value_mapping && value_mapping.kind_of?(Hash)
      if value.kind_of?(Array)
        transformation = t(:map_array, -> v { value_mapping[v] })
        new_value = transformation.call(value)
        attributes[key] = new_value
      elsif value.kind_of?(String) || value.kind_of?(Symbol)
        transformation = t(:map_value, key, -> v { value_mapping[v.to_s] })
        new_value = transformation.call({key => value})
        attributes[key] = new_value[key]
      end
    elsif value_mapping && value_mapping.kind_of?(Proc)
      attributes[key] = value_mapping.call(value)
    end
  end
  attributes
end