class HashMath::Record

A Record serves as a prototype for a Hash. It will allow the output of hashes conforming to a strict (make!) or non-strict (make) shape.

Attributes

prototype[R]

Public Class Methods

new(keys = [], base_value = nil) click to toggle source
# File lib/hash_math/record.rb, line 18
def initialize(keys = [], base_value = nil)
  @prototype = keys.map { |key| [key, base_value] }.to_h

  freeze
end

Public Instance Methods

make(hash = {}, bound = false) click to toggle source
# File lib/hash_math/record.rb, line 28
def make(hash = {}, bound = false)
  hash.each_with_object(shallow_copy_prototype) do |(key, value), memo|
    next unless assert_key_in_bounds(key, bound)

    memo[key] = value
  end
end
make!(hash = {}) click to toggle source
# File lib/hash_math/record.rb, line 24
def make!(hash = {})
  make(hash, true)
end

Private Instance Methods

assert_key_in_bounds(key, bound) click to toggle source

raise error if key is not in key set and bound is true return true if key is in key set and bound is false return false if key is not in key set and bound is false

# File lib/hash_math/record.rb, line 43
def assert_key_in_bounds(key, bound)
  raise KeyOutOfBoundsError, "[#{key}] for: #{keys}" if not_key?(key) && bound

  key?(key)
end
not_key?(key) click to toggle source
# File lib/hash_math/record.rb, line 49
def not_key?(key)
  !key?(key)
end
shallow_copy_prototype() click to toggle source
# File lib/hash_math/record.rb, line 53
def shallow_copy_prototype
  {}.merge(prototype)
end