Class: EasyTalk::SchemaDefinition

Inherits:
Object
  • Object
show all
Extended by:
T::AllOf, T::AnyOf, T::OneOf, T::Sig
Defined in:
lib/easy_talk/schema_definition.rb

Overview

EasyTalk SchemaDefinition

SchemaDefinition provides the methods for defining a schema within the define_schema block. The @schema is a hash that contains the unvalidated schema definition for the model. A SchemaDefinition instanace is the passed to the Builder.build_schema method to validate and compile the schema.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from T::AnyOf

[]

Methods included from T::OneOf

[]

Methods included from T::AllOf

[]

Constructor Details

#initialize(name, schema = {}) ⇒ SchemaDefinition

Returns a new instance of SchemaDefinition.



21
22
23
24
# File 'lib/easy_talk/schema_definition.rb', line 21

def initialize(name, schema = {})
  @schema = schema
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



19
20
21
# File 'lib/easy_talk/schema_definition.rb', line 19

def name
  @name
end

#schemaObject (readonly)

Returns the value of attribute schema.



19
20
21
# File 'lib/easy_talk/schema_definition.rb', line 19

def schema
  @schema
end

Instance Method Details

#compose(*subschemas) ⇒ Object



32
33
34
35
# File 'lib/easy_talk/schema_definition.rb', line 32

def compose(*subschemas)
  @schema[:subschemas] ||= []
  @schema[:subschemas] += subschemas
end

#optional?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/easy_talk/schema_definition.rb', line 65

def optional?
  @schema[:optional]
end

#property(name, type, constraints = {}, &blk) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/easy_talk/schema_definition.rb', line 40

def property(name, type, constraints = {}, &blk)
  validate_property_name(name)
  @schema[:properties] ||= {}

  if block_given?
    property_schema = SchemaDefinition.new(name)
    property_schema.instance_eval(&blk)

    @schema[:properties][name] = {
      type:,
      constraints:,
      properties: property_schema
    }
  else
    @schema[:properties][name] = { type:, constraints: }
  end
end

#validate_property_name(name) ⇒ Object



58
59
60
61
62
63
# File 'lib/easy_talk/schema_definition.rb', line 58

def validate_property_name(name)
  return if name.to_s.match?(/^[A-Za-z_][A-Za-z0-9_]*$/)

  raise InvalidPropertyNameError,
        "Invalid property name '#{name}'. Must start with letter/underscore and contain only letters, numbers, underscores"
end