Class: TypedModel::Types

Inherits:
Object
  • Object
show all
Defined in:
lib/typed_model/types.rb

Overview

Supported Types/Type coercion

Type checking methods (e.g. boolean, integer, etc..) should return value of type if "reasonably" coercible, otherwise nil.

"Reasonable" = reasonable valid over the wire data for type. E.g. String 'true' is reasonable for a declared :boolean. Likewise, boolean is reasonable for declared string, but Hash not so much.

Constant Summary collapse

PRIMITIVE_CLASSES =
Set.new([String, TrueClass, FalseClass, Integer, Float])

Class Method Summary collapse

Class Method Details

.boolean(v) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/typed_model/types.rb', line 38

def boolean(v)
  case v
  when 'true', true
    true
  when 'false', false
    false
  end
end

.integer(v) ⇒ Object



47
48
49
50
51
# File 'lib/typed_model/types.rb', line 47

def integer(v)
  Integer(v)
rescue StandardError
  nil
end

.map(v) ⇒ Object



53
54
55
# File 'lib/typed_model/types.rb', line 53

def map(v)
  maplike?(v) ? v : nil
end

.recognized?(t) ⇒ Boolean

Returns:

  • (Boolean)


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

def recognized?(t)
  respond_to?(t)
end

.seq(v) ⇒ Object



57
58
59
60
61
62
# File 'lib/typed_model/types.rb', line 57

def seq(v)
  return nil if v.nil?
  return v if v.is_a?(Array)
  return v.to_a if v.respond_to?(:to_a) && !maplike?(v)
  nil
end

.string(v) ⇒ Object



64
65
66
# File 'lib/typed_model/types.rb', line 64

def string(v)
  primitive?(v) ? v.to_s : nil
end

.timestamp(v) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/typed_model/types.rb', line 28

def timestamp(v)
  if v.respond_to?(:monday?)
    v
  else
    Time.parse(v)
  end
rescue StandardError
  nil
end

.typecast(sym, value) ⇒ Object



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

def typecast(sym, value)
  type_casted = send(sym, value)
  type_casted.nil? ? value : type_casted
end