class ValueSemantics::HashCoercer

Attributes

key_coercer[R]
value_coercer[R]

Public Class Methods

new(key_coercer:, value_coercer:) click to toggle source
# File lib/value_semantics/hash_coercer.rb, line 5
def initialize(key_coercer:, value_coercer:)
  @key_coercer, @value_coercer = key_coercer, value_coercer
  freeze
end

Public Instance Methods

call(obj) click to toggle source
# File lib/value_semantics/hash_coercer.rb, line 10
def call(obj)
  hash = coerce_to_hash(obj)
  return obj unless hash

  {}.tap do |result|
    hash.each do |key, value|
      r_key = key_coercer.(key)
      r_value = value_coercer.(value)
      result[r_key] = r_value
    end
  end
end

Private Instance Methods

coerce_to_hash(obj) click to toggle source
# File lib/value_semantics/hash_coercer.rb, line 25
def coerce_to_hash(obj)
  return nil unless obj.respond_to?(:to_h)
  obj.to_h
end