Class: HashMath::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_math/mapper.rb,
lib/hash_math/mapper/lookup.rb,
lib/hash_math/mapper/mapping.rb

Overview

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.

Defined Under Namespace

Classes: Lookup, Mapping

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mappings = []) ⇒ Mapper

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



21
22
23
24
25
26
# File 'lib/hash_math/mapper.rb', line 21

def initialize(mappings = [])
  mappings          = Mapping.array(mappings)
  @mappings_by_name = pivot_by_name(mappings)

  freeze
end

Instance Attribute Details

#mappings_by_nameObject (readonly)

Returns the value of attribute mappings_by_name.



17
18
19
# File 'lib/hash_math/mapper.rb', line 17

def mappings_by_name
  @mappings_by_name
end

Instance Method Details

#add(name, object) ⇒ Object

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

Raises:

  • (ArgumentError)


38
39
40
41
42
# 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) ⇒ Object

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

Raises:

  • (ArgumentError)


30
31
32
33
34
# 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) ⇒ Object

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



46
47
48
# File 'lib/hash_math/mapper.rb', line 46

def map(hash)
  map!({}.merge(hash || {}))
end

#map!(hash) ⇒ Object

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



51
52
53
54
55
# 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