class HecksPlugins::JSONValidator::SchemaParser
Create a JSON Schema from an object
Constants
- HECKS_NUMBER_TYPES
- JSON_TYPES
Attributes
domain_module[R]
object[R]
properties[R]
required_fields[R]
schema[R]
Public Class Methods
new(domain_module:, object: @domain_module = domain_module)
click to toggle source
# File lib/parsers/schema_parser.rb, line 9 def initialize domain_module:, object: @domain_module = domain_module @object = object @properties = {} end
Public Instance Methods
call()
click to toggle source
# File lib/parsers/schema_parser.rb, line 15 def call parse_required_fields object.attributes.each { |a| parse_property(a) } build_schema self end
Private Instance Methods
build_schema()
click to toggle source
# File lib/parsers/schema_parser.rb, line 26 def build_schema @schema = { "type" => "object", "required" => required_fields, "properties" => properties } end
get_json_type(attribute)
click to toggle source
# File lib/parsers/schema_parser.rb, line 38 def get_json_type attribute result = attribute.type.downcase return 'array' if attribute.list? return 'number' if HECKS_NUMBER_TYPES.include?(result) return 'object' unless JSON_TYPES.include?(result) result end
parse_property(attribute)
click to toggle source
# File lib/parsers/schema_parser.rb, line 55 def parse_property(attribute) type = get_json_type(attribute) name = attribute.name properties[name] = case type when 'object' then schema_for_attribute(attribute) when 'array' { "type" => 'array', "items" => schema_for_attribute(attribute) } else { "type" => type } end end
parse_required_fields()
click to toggle source
# File lib/parsers/schema_parser.rb, line 34 def parse_required_fields @required_fields = object.attributes.map{ |a| a.name } end
schema_for_attribute(attribute)
click to toggle source
# File lib/parsers/schema_parser.rb, line 47 def schema_for_attribute attribute return {} if attribute.reference? self.class.new( domain_module: domain_module, object: domain_module.find(attribute.type) ).call.schema end