Sha256: 0fbaaa1943dc6bf49702c6cc9ab5725014b7aab1a4e7fc4c36701b453bdb1dba
Contents?: true
Size: 1.47 KB
Versions: 4
Compression:
Stored size: 1.47 KB
Contents
class SchemaSerializer class Schema attr_reader :type, :nullable, :items, :required, :properties def initialize(hash = {}) @type = hash["type"] @nullable = !!hash["nullable"] 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, _hash), obj| obj[column] = self.class.new(_hash) } end end 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 private def get_value(object, column) return object[column] || object[column.to_sym] if object.is_a?(Hash) value = object.public_send(column) return value if !object.respond_to?(:defined_enums) || !object.defined_enums.has_key?(column) object.defined_enums[column][value] end end end
Version data entries
4 entries across 4 versions & 1 rubygems