Class: SchemaBuilder
- Inherits:
-
Object
- Object
- SchemaBuilder
- Defined in:
- lib/schema_builder/schema_builder.rb
Overview
Define the SchemaBuilder class
Instance Method Summary collapse
-
#generate ⇒ Object
Generate the schema for the object and included fields.
-
#initialize(object, included) ⇒ SchemaBuilder
constructor
Initialize the class with the object and included fields.
Constructor Details
#initialize(object, included) ⇒ SchemaBuilder
Initialize the class with the object and included fields
7 8 9 10 |
# File 'lib/schema_builder/schema_builder.rb', line 7 def initialize(object, included) @object = object @included = included end |
Instance Method Details
#generate ⇒ Object
Generate the schema for the object and included fields
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/schema_builder/schema_builder.rb', line 13 def generate # Set the type of the schema to "object" schema = { type: 'object' } # Initialize the "properties" and "required" fields in the schema schema[:properties] = {} schema[:required] = [] # Iterate over the attributes and relationships in the object (@object[:attributes] || {}).each do |property, value| # Add the property to the schema schema[:properties][property] = { type: value.class.name.downcase } end (@object[:relationships] || {}).each do |property, value| # Add the property to the schema schema[:properties][property] = { type: 'object' } # Generate a schema for the related objects using recursion if value[:data].is_a?(Array) # Nested array - generate a schema for each item in the array schema[:properties][property][:type] = 'array' schema[:properties][property][:items] = value[:data].map do |item| # Find the included object with the matching type and ID included_object = @included[item[:type]][item[:id]] # Generate a schema for the included object SchemaBuilder.new(included_object, @included).generate end else # Nested object - generate a schema for it # Find the included object with the matching type and ID included_object = @included[value[:data][:type]][value[:data][:id]] # Generate a schema for the included object schema[:properties][property][:properties] = SchemaBuilder.new(included_object, @included).generate end # Return the generated schema schema end end |