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.
133 134 135 |
# File 'lib/strong_json/type.rb', line 133 def initialize(fields) @fields = fields end |
Instance Method Details
#coerce(object, path: []) ⇒ Object
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/strong_json/type.rb', line 137 def coerce(object, path: []) unless object.is_a?(Hash) raise Error.new(path: path, type: self, value: object) end # @type var result: ::Hash<Symbol, any> 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
184 185 186 187 188 |
# File 'lib/strong_json/type.rb', line 184 def except(*keys) Object.new(keys.each.with_object(@fields.dup) do |key, hash| hash.delete key end) end |
#merge(fields) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/strong_json/type.rb', line 171 def merge(fields) # @type var fs: Hash<Symbol, _Schema<any>> fs = case fields when Object fields.instance_variable_get(:"@fields") when Hash fields end Object.new(@fields.merge(fs)) end |
#test_value_type(path, type, value) {|v| ... } ⇒ Object
162 163 164 165 166 167 168 169 |
# File 'lib/strong_json/type.rb', line 162 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
190 191 192 193 194 195 196 197 198 199 |
# File 'lib/strong_json/type.rb', line 190 def to_s # @type var fields: ::Array<String> fields = [] @fields.each do |name, type| fields << "#{name}: #{type}" end "object(#{fields.join(', ')})" end |