Class: SchemaSerializer::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/schema_serializer/schema.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Schema

Returns a new instance of Schema.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/schema_serializer/schema.rb', line 5

def initialize(hash = {})
  @type     = hash["type"]
  @nullable = !hash["nullable"].nil?

  case type
  when "array"
    @items = self.class.new(hash.fetch("items"))
  when "object", nil
    @required = hash["required"] || []
    @properties = hash.fetch("properties").each_with_object({}) { |(column, property), obj|
      obj[column] = self.class.new(property)
    }
  end
end

Instance Attribute Details

#itemsObject (readonly)

Returns the value of attribute items.



3
4
5
# File 'lib/schema_serializer/schema.rb', line 3

def items
  @items
end

#nullableObject (readonly)

Returns the value of attribute nullable.



3
4
5
# File 'lib/schema_serializer/schema.rb', line 3

def nullable
  @nullable
end

#propertiesObject (readonly)

Returns the value of attribute properties.



3
4
5
# File 'lib/schema_serializer/schema.rb', line 3

def properties
  @properties
end

#requiredObject (readonly)

Returns the value of attribute required.



3
4
5
# File 'lib/schema_serializer/schema.rb', line 3

def required
  @required
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/schema_serializer/schema.rb', line 3

def type
  @type
end

Instance Method Details

#serialize(object) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/schema_serializer/schema.rb', line 20

def serialize(object)
  return nil if nullable && object.nil?

  case type
  when "integer"
    object.to_i
  when "number"
    object.to_f
  when "string"
    object.to_s
  when "boolean"
    !!object
  when "array"
    object.map { |item| items.serialize(item) }
  else
    not_enough_columns = required - properties.keys
    raise RequiredNotDefined, not_enough_columns.join(", ") unless not_enough_columns.empty?

    properties.each_with_object({}) { |(column, schema), obj|
      obj[column] = schema.serialize(get_value(object, column))
    }
  end
end