Module: Id::Coercion

Extended by:
Coercion
Included in:
Coercion
Defined in:
lib/id/coercion.rb

Instance Method Summary collapse

Instance Method Details

#coerce(value, type) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/id/coercion.rb', line 9

def coerce(value, type)
  return value.map { |v| coerce(v, type) } if value.is_a? Option
  return (value || []).map { |v| coerce(v, type.first) } if type.is_a? Array
  return value if value.is_a? type
  return type.new(value) if type.include? Id::Model

  coercion = coercions.fetch([value.class, type], false)
  fail Id::CoercionError, [value.class, type] unless coercion
  coercion.call(value)
end

#register(from, to, &coercion) ⇒ Object



4
5
6
7
# File 'lib/id/coercion.rb', line 4

def register(from, to, &coercion)
  warn "Id - Overwriting existing coercion" if coercions.has_key?([from, to])
  coercions[[from, to]] = coercion
end