Class: TSJSON::ObjectType
Instance Method Summary collapse
- #compile ⇒ Object
- #field(name) ⇒ Object (also: #index)
- #fields ⇒ Object
- #fields_map ⇒ Object
-
#initialize(fields_map = nil, &block) ⇒ ObjectType
constructor
A new instance of ObjectType.
- #to_s ⇒ Object
- #validate(object) ⇒ Object
Methods inherited from Base
Constructor Details
#initialize(fields_map = nil, &block) ⇒ ObjectType
Returns a new instance of ObjectType.
3 4 5 6 7 |
# File 'lib/types/object.rb', line 3 def initialize(fields_map = nil, &block) super() @fields_map = fields_map&.transform_keys!(&:to_s) @resolve_fields = block end |
Instance Method Details
#compile ⇒ Object
30 31 32 33 34 35 |
# File 'lib/types/object.rb', line 30 def compile return if @compiled @compiled = true fields.each { |f| f[:type].compile } end |
#field(name) ⇒ Object Also known as: index
15 16 17 18 19 20 |
# File 'lib/types/object.rb', line 15 def field(name) f = fields_map.dig(name, :type) raise "Can't access index #{name} of #{self.class.name}" unless f f end |
#fields ⇒ Object
9 10 11 12 13 |
# File 'lib/types/object.rb', line 9 def fields @fields = fields_map.map { |k, v| v.merge({ name: k }) } unless @fields @fields end |
#fields_map ⇒ Object
23 24 25 26 27 28 |
# File 'lib/types/object.rb', line 23 def fields_map unless @fields_map @fields_map = @resolve_fields.call&.transform_keys!(&:to_s) end @fields_map end |
#to_s ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/types/object.rb', line 75 def to_s "{\n#{ fields.map do |f| name = f[:name] type = f[:type].to_s optional = f[:optional] " #{name}#{optional ? '?' : ''}: #{type}" end.join("\n") }\n}" end |
#validate(object) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/types/object.rb', line 37 def validate(object) unless object.is_a?(::Hash) raise ScalarValidationError.new( expected_type: 'Object', received_type: object.class.name, received_value: object ) end object = object&.transform_keys!(&:to_s) keys = object.keys errors = [] fields.each do |f| name = f[:name] type = f[:type] optional = f[:optional] value = object[name] keys.delete(name) has_field = object.key?(name) next if optional && !has_field raise RequiredFieldError.new if !optional && !has_field type.validate(value) rescue ValidationError => e errors.push({ field: name, error: e }) end keys.each do |name| errors.push({ field: name, error: UnexpectedFieldError.new }) end raise ObjectValidationError.new(errors: errors) if errors.length > 0 true end |