Module: Structure::Types

Extended by:
Types
Included in:
Types
Defined in:
lib/structure/types.rb

Overview

Type coercion methods for converting values to specific types

Instance Method Summary collapse

Instance Method Details

#array(element_type) ⇒ Object

Create coercer for array elements



29
30
31
32
# File 'lib/structure/types.rb', line 29

def array(element_type)
  element_coercer = coerce(element_type)
  ->(array) { array.map { |element| element_coercer.call(element) } }
end

#booleanObject

Boolean conversion



14
15
16
# File 'lib/structure/types.rb', line 14

def boolean
  @boolean ||= ->(val) { BOOLEAN_TRUTHY.include?(val) }
end

#coerce(type) ⇒ Object

Main factory method for creating type coercers



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/structure/types.rb', line 35

def coerce(type)
  case type
  when :boolean
    boolean
  when Class
    if type.name && Kernel.respond_to?(type.name)
      kernel(type)
    elsif type.respond_to?(:parse)
      structure(type)
    else
      type
    end
  when Array
    if type.length == 1
      array(type.first)
    else
      type
    end
  else
    type
  end
end

#kernel(type) ⇒ Object

Generic handler for classes with kernel methods (String, Integer, Float, etc.)



19
20
21
# File 'lib/structure/types.rb', line 19

def kernel(type)
  ->(val) { Kernel.send(type.name, val) }
end

#structure(type) ⇒ Object

Handler for nested Structure classes



24
25
26
# File 'lib/structure/types.rb', line 24

def structure(type)
  ->(val) { type.parse(val) }
end