Class: Anyway::TypeCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/anyway/type_casting.rb

Overview

TypeCaster is an object responsible for type-casting. It uses a provided types registry and mapping, and also accepts a fallback typecaster.

Instance Method Summary collapse

Constructor Details

#initialize(mapping, registry: TypeRegistry.default, fallback: ::Anyway::AutoCast) ⇒ TypeCaster

Returns a new instance of TypeCaster.



87
88
89
90
91
# File 'lib/anyway/type_casting.rb', line 87

def initialize(mapping, registry: TypeRegistry.default, fallback: ::Anyway::AutoCast)
  @mapping = mapping.deep_dup
  @registry = registry
  @fallback = fallback
end

Instance Method Details

#coerce(key, val, config: mapping) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/anyway/type_casting.rb', line 93

def coerce(key, val, config: mapping)
  caster_config = config[key.to_sym]

  return fallback.coerce(key, val) unless caster_config

  case caster_config
  in array:, type:, **nil
    registry.deserialize(val, type, array: array)
  in Hash
    return val unless val.is_a?(Hash)

    caster_config.each do |k, v|
      ks = k.to_s
      next unless val.key?(ks)

      val[ks] = coerce(k, val[ks], config: caster_config)
    end

    val
  else
    registry.deserialize(val, caster_config)
  end
end