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
- #to_s ⇒ Object
Constructor Details
#initialize(fields) ⇒ Object
Returns a new instance of Object.
78 79 80 |
# File 'lib/strong_json/type.rb', line 78 def initialize(fields) @fields = fields end |
Instance Method Details
#coerce(object, path: []) ⇒ Object
82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/strong_json/type.rb', line 82 def coerce(object, path: []) unless object.is_a?(Hash) raise Error.new(path: path, type: self, value: object) end result = {} @fields.each do |name, ty| value = ty.coerce(object.has_key?(name) ? object[name] : NONE, path: path + [name]) result[name] = value if object.has_key?(name) end result end |
#except(*keys) ⇒ Object
105 106 107 108 109 |
# File 'lib/strong_json/type.rb', line 105 def except(*keys) Object.new(keys.each.with_object(@fields.dup) do |key, hash| hash.delete key end) end |
#merge(fields) ⇒ Object
97 98 99 100 101 102 103 |
# File 'lib/strong_json/type.rb', line 97 def merge(fields) if fields.is_a?(Object) fields = Object.instance_variable_get("@fields") end Object.new(@fields.merge(fields)) end |
#to_s ⇒ Object
111 112 113 114 115 116 117 118 119 |
# File 'lib/strong_json/type.rb', line 111 def to_s fields = [] @fields.each do |name, type| fields << "#{name}: #{type}" end "object(#{fields.join(', ')})" end |