class HashMath::Mapper

A Mapper instance can hold multiple constant-time object lookups and then is able to map a hash to its corresponding lookup values. It's main use-case is to fill in missing or update existing key-value pairs with its corresponding relationships.

Attributes

mappings_by_name[R]

Public Class Methods

new(mappings = []) click to toggle source

Accepts an array of Mapping instances of hashes containing the Mapping instance attributes to initialize.

# File lib/hash_math/mapper.rb, line 21
def initialize(mappings = [])
  mappings          = Mapping.array(mappings)
  @mappings_by_name = pivot_by_name(mappings)

  freeze
end

Public Instance Methods

add(name, object) click to toggle source

Add a lookup record to this instance's lookup dataset. Raises ArgumentError if name is blank.

# File lib/hash_math/mapper.rb, line 38
def add(name, object)
  raise ArgumentError, 'name is required' if name.to_s.empty?

  tap { mappings_by_name.fetch(name.to_s).add(object) }
end
add_each(name, objects) click to toggle source

Add an enumerable list of lookup records to this instance's lookup dataset. Raises ArgumentError if name is blank.

# File lib/hash_math/mapper.rb, line 30
def add_each(name, objects)
  raise ArgumentError, 'name is required' if name.to_s.empty?

  tap { objects.each { |o| add(name, o) } }
end
map(hash) click to toggle source

Returns a new hash with the added/updated key-value pairs. Note that this only does a shallow copy using Hash#merge.

# File lib/hash_math/mapper.rb, line 46
def map(hash)
  map!({}.merge(hash || {}))
end
map!(hash) click to toggle source

Mutates the inpuuted hash with the added/updated key-value pairs.

# File lib/hash_math/mapper.rb, line 51
def map!(hash)
  mappings_by_name.values.each_with_object(hash) do |mapping, _memo|
    mapping.map!(hash)
  end
end

Private Instance Methods

pivot_by_name(array) click to toggle source
# File lib/hash_math/mapper.rb, line 59
def pivot_by_name(array)
  array.each_with_object({}) do |object, memo|
    memo[object.name.to_s] = object
  end
end