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(key, hash = {}) ⇒ Schema

Returns a new instance of Schema.



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

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

  case type
  when "array"
    @items = self.class.new(@key, hash.fetch("items"))
  when "object", nil
    @required = hash["required"] || []
    @properties = hash.fetch("properties").each_with_object({}) { |(column, property), obj|
      obj[column] = self.class.new(column, 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

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
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



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

def serialize(object)
  if object.nil?
    return nil if nullable
    raise NullValue, "#{key} is not allowed to be null" if SchemaSerializer.config.raise_on_null
  end

  case type
  when "integer"
    object.to_i
  when "number"
    object.to_f
  when "string"
    object.to_s
  when "boolean"
    !!object
  when "array"
    serialize_array(object)
  else
    serialize_object(object)
  end
end