Class: Jsapi::Meta::Existence

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/jsapi/meta/existence.rb

Overview

Combines the presence concepts of the #present? method and JSON Schema by four levels of existence.

Constant Summary collapse

ALLOW_OMITTED =

The parameter or property can be omitted, corresponds to the opposite of required as specified by JSON Schema.

new(1)
ALLOW_NIL =

The parameter or property value can be nil, corresponds to nullable: true as specified by JSON Schema.

new(2)
ALLOW_EMPTY =

The parameter or property value must respond to nil? with false.

new(3)
PRESENT =

The parameter or property value must respond to present? with true or must be false.

new(4)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(level) ⇒ Existence

Creates a new instance with the specified level.



14
15
16
# File 'lib/jsapi/meta/existence.rb', line 14

def initialize(level)
  @level = level
end

Instance Attribute Details

#levelObject (readonly)

The level of existence.



11
12
13
# File 'lib/jsapi/meta/existence.rb', line 11

def level
  @level
end

Class Method Details

.from(value) ⇒ Object

Creates a new instance from value.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/jsapi/meta/existence.rb', line 34

def self.from(value)
  return value if value.is_a?(Existence)

  case value
  when :present, true
    PRESENT
  when :allow_empty
    ALLOW_EMPTY
  when :allow_nil, :allow_null
    ALLOW_NIL
  when :allow_omitted, false, nil
    ALLOW_OMITTED
  else
    raise ArgumentError, "invalid existence: #{value}"
  end
end

Instance Method Details

#<=>(other) ⇒ Object

:nodoc:



55
56
57
# File 'lib/jsapi/meta/existence.rb', line 55

def <=>(other) # :nodoc:
  level <=> other.level
end

#==(other) ⇒ Object

:nodoc:



51
52
53
# File 'lib/jsapi/meta/existence.rb', line 51

def ==(other) # :nodoc:
  other.is_a?(Existence) && level == other.level
end

#inspectObject

:nodoc:



59
60
61
# File 'lib/jsapi/meta/existence.rb', line 59

def inspect # :nodoc:
  "#<#{self.class.name} level: #{level}>"
end

#reach?(object) ⇒ Boolean

Returns true if object reaches the level of existence, false otherwise.

Returns:

  • (Boolean)


64
65
66
# File 'lib/jsapi/meta/existence.rb', line 64

def reach?(object)
  (object.null? ? 2 : object.empty? ? 3 : 4) >= level
end