Module: Structure::Types

Defined in:
lib/structure/types.rb

Overview

Type coercion methods for converting values to specific types

Class Method Summary collapse

Class Method Details

.coerce(type, context = nil) ⇒ Proc?

Main factory method for creating type coercers

Examples:

Boolean type

coerce(:boolean) # => boolean proc

Self-referential types

coerce(:self) # => proc that calls context.parse

Kernel types

coerce(Integer) # => proc that calls Kernel.Integer

Array types

coerce([String]) # => proc that coerces array elements to String

Parseable types

coerce(Date) # => proc that calls Date.parse

No coercion

coerce(nil) # => nil

Custom lambdas

coerce(->(val) { val.upcase }) # => returns the lambda itself

Lazy-resolved classes

coerce("MyClass") # => proc that resolves and coerces to MyClass

Parameters:

  • type (Class, Symbol, Array, String, nil)

    Type specification

  • context (Class, nil) (defaults to: nil)

    Context class for lazy-loading and self-referential types

Returns:

  • (Proc, nil)

    Coercion proc or nil if no coercion needed

Raises:

  • (ArgumentError)

    If type is a Hash instance (typed hashes not yet supported) or unsupported type



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/structure/types.rb', line 42

def coerce(type, context = nil)
  case type
  when :boolean
    boolean
  when :self
    self_referential(context)
  when ->(t) { t.respond_to?(:name) && t.name && Kernel.respond_to?(t.name) }
    kernel(type)
  when ->(t) { t.is_a?(Array) && t.length == 1 }
    array(type.first, context)
  when ->(t) { t.respond_to?(:parse) }
    parseable(type)
  when nil
    type
  when ->(t) { t.respond_to?(:call) }
    type
  when String
    lazy_class(type, context)
  else
    raise ArgumentError, "Cannot specify #{type.inspect} as type"
  end
end