Sha256: 8f3f29550f689cd7e163158327b30058b6a8d97be1f2609854f8fbe516d55571

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 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 = {}
      @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)
        property_schema.instance_eval(&blk)
        @schema[:properties][name] = property_schema
      else
        @schema[:properties][name] = { type:, constraints: }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
easy_talk-0.1.9 lib/easy_talk/schema_definition.rb