Sha256: 2bda7e8fabebecc66110bd07aad890111f61557ec46724414d1c3aeaaf3f75d9

Contents?: true

Size: 1.45 KB

Versions: 3

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

require_relative 'keywords'

module EasyTalk
  #
  #= 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.
  class SchemaDefinition
    extend T::Sig
    extend T::AnyOf
    extend T::OneOf
    extend T::AllOf

    attr_reader :name, :schema

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

    EasyTalk::KEYWORDS.each do |keyword|
      define_method(keyword) do |*values|
        @schema[keyword] = values.size > 1 ? values : values.first
      end
    end

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

    sig do
      params(name: T.any(Symbol, String), type: T.untyped, constraints: T.untyped, blk: T.nilable(T.proc.void)).void
    end
    def property(name, type, **constraints, &blk)
      @schema[:properties] ||= {}

      if block_given?
        property_schema = SchemaDefinition.new(name, constraints)
        property_schema.instance_eval(&blk)
        @schema[:properties][name] = property_schema
      else
        @schema[:properties][name] = { type:, constraints: }
      end
    end

    def optional?
      @schema[:optional]
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
easy_talk-0.2.1 lib/easy_talk/schema_definition.rb
easy_talk-0.2.0 lib/easy_talk/schema_definition.rb
easy_talk-0.1.10 lib/easy_talk/schema_definition.rb