Class: StrongJSON::Type::Object
- Inherits:
-
Object
- Object
- StrongJSON::Type::Object
- Includes:
- Match
- 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
Methods included from Match
Constructor Details
#initialize(fields) ⇒ Object
Returns a new instance of Object.
131 132 133 |
# File 'lib/strong_json/type.rb', line 131 def initialize(fields) @fields = fields end |
Instance Method Details
#coerce(object, path: []) ⇒ Object
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/strong_json/type.rb', line 135 def coerce(object, path: []) unless object.is_a?(Hash) raise Error.new(path: path, type: self, value: object) end result = {} object.each do |key, value| unless @fields.key?(key) raise UnexpectedFieldError.new(path: path + [key], value: value) end end @fields.each do |key, type| value = object.key?(key) ? object[key] : NONE test_value_type(path + [key], type, value) do |v| result[key] = v end end result end |
#except(*keys) ⇒ Object
176 177 178 179 180 |
# File 'lib/strong_json/type.rb', line 176 def except(*keys) Object.new(keys.each.with_object(@fields.dup) do |key, hash| hash.delete key end) end |
#merge(fields) ⇒ Object
168 169 170 171 172 173 174 |
# File 'lib/strong_json/type.rb', line 168 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
159 160 161 162 163 164 165 166 |
# File 'lib/strong_json/type.rb', line 159 def test_value_type(path, type, value) v = type.coerce(value, path: path) return if NONE.equal?(v) || NONE.equal?(type) return if type.is_a?(Optional) && NONE.equal?(value) yield(v) end |
#to_s ⇒ Object
182 183 184 185 186 187 188 189 190 |
# File 'lib/strong_json/type.rb', line 182 def to_s fields = [] @fields.each do |name, type| fields << "#{name}: #{type}" end "object(#{fields.join(', ')})" end |