Method: Attributor::Hash#merge

Defined in:
lib/attributor/types/hash.rb

#merge(h) ⇒ Object



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/attributor/types/hash.rb', line 582

def merge(h)
  case h
  when self.class
    self.class.new(contents.merge(h.contents))
  when Attributor::Hash
    source_key_type = self.class.key_type
    source_value_type = self.class.value_type
    # Allow merging hashes, but we'll need to coerce keys and/or values if they aren't the same type
    coerced_contents = h.contents.each_with_object({}) do |(key, val), object|
      k = (source_key_type && !k.is_a?(source_key_type)) ? source_key_type.load(key) : key
      v = (source_value_type && !k.is_a?(source_value_type)) ? source_value_type.load(val) : val
      object[k] = v
    end
    self.class.new(contents.merge(coerced_contents))
  else
    raise TypeError, "no implicit conversion of #{h.class} into Attributor::Hash"
  end
end