Class: StrongJSON::Type::Base

Inherits:
Object
  • Object
show all
Includes:
Match
Defined in:
lib/strong_json/type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Match

#===, #=~

Constructor Details

#initialize(type) ⇒ Base

Returns a new instance of Base.



24
25
26
# File 'lib/strong_json/type.rb', line 24

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



22
23
24
# File 'lib/strong_json/type.rb', line 22

def type
  @type
end

Instance Method Details

#coerce(value, path: []) ⇒ Object

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/strong_json/type.rb', line 49

def coerce(value, path: [])
  raise Error.new(value: value, type: self, path: path) unless test(value)
  raise IllegalTypeError.new(type: self) if path == [] && @type == :ignored

  case type
  when :ignored
    NONE
  when :symbol
    value.to_sym
  else
    value
  end
end

#test(value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/strong_json/type.rb', line 28

def test(value)
  case @type
  when :ignored
    true
  when :any
    true
  when :number
    value.is_a?(Numeric)
  when :string
    value.is_a?(String)
  when :boolean
    value == true || value == false
  when :numeric
    value.is_a?(Numeric) || value.is_a?(String) && /\A[\-\+]?[\d.]+\Z/ =~ value
  when :symbol
    value.is_a?(String) || value.is_a?(Symbol)
  else
    false
  end
end

#to_sObject



63
64
65
# File 'lib/strong_json/type.rb', line 63

def to_s
  @type.to_s
end