Module: GraphWeaver::InputStruct::ClassMethods

Includes:
Kernel
Defined in:
lib/graph_weaver/input_struct.rb

Instance Method Summary collapse

Instance Method Details

#coerce(value) ⇒ Object

Build from a plain hash (underscored keys, Symbol or String): enums accept their wire values, nested inputs accept hashes; the struct's types are enforced on construction, and unknown keys raise with a spellchecked hint.



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/graph_weaver/input_struct.rb', line 45

def coerce(value)
  return value if value.is_a?(self)

  # a typo'd key must not silently drop off the wire
  GraphWeaver::Hints.validate_keys!(self, value)

  fields = T.unsafe(self).const_get(:FIELDS)
  T.unsafe(self).new(**fields.to_h do |field|
    raw = value.key?(field.prop) ? value[field.prop] : value[field.prop.to_s]
    [field.prop, raw.nil? || field.coercer.nil? ? raw : field.coercer.call(raw)]
  end)
end