Class: StrongJSON::Type::Object
- Inherits:
-
Object
- Object
- StrongJSON::Type::Object
- Defined in:
- lib/strong_json/type.rb
Instance Method Summary collapse
- #coerce(object, path: []) ⇒ Object
- #except(*keys) ⇒ Object
-
#initialize(fields) ⇒ Object
constructor
A new instance of Object.
- #merge(fields) ⇒ Object
- #test_value_type(path, type, value) {|v| ... } ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(fields) ⇒ Object
Returns a new instance of Object.
81 82 83 |
# File 'lib/strong_json/type.rb', line 81 def initialize(fields) @fields = fields end |
Instance Method Details
#coerce(object, path: []) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/strong_json/type.rb', line 85 def coerce(object, path: []) unless object.is_a?(Hash) raise Error.new(path: path, type: self, value: object) end result = {} all_keys = (@fields.keys + object.keys).sort.uniq all_keys.each do |key| type = @fields.has_key?(key) ? @fields[key] : NONE value = object.has_key?(key) ? object[key] : NONE test_value_type(path + [key], type, value) do |v| result[key] = v end end result end |
#except(*keys) ⇒ Object
126 127 128 129 130 |
# File 'lib/strong_json/type.rb', line 126 def except(*keys) Object.new(keys.each.with_object(@fields.dup) do |key, hash| hash.delete key end) end |
#merge(fields) ⇒ Object
118 119 120 121 122 123 124 |
# File 'lib/strong_json/type.rb', line 118 def merge(fields) if fields.is_a?(Object) fields = Object.instance_variable_get("@fields") end Object.new(@fields.merge(fields)) end |
#test_value_type(path, type, value) {|v| ... } ⇒ Object
105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/strong_json/type.rb', line 105 def test_value_type(path, type, value) if NONE.equal?(type) && !NONE.equal?(value) raise UnexpectedFieldError.new(path: path, value: value) end v = type.coerce(value, path: path) return if NONE.equal?(v) || NONE.equal?(type) return if type.is_a?(Optional) && v == nil yield(v) end |
#to_s ⇒ Object
132 133 134 135 136 137 138 139 140 |
# File 'lib/strong_json/type.rb', line 132 def to_s fields = [] @fields.each do |name, type| fields << "#{name}: #{type}" end "object(#{fields.join(', ')})" end |