Class: EasyTalk::Builders::BaseBuilder

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/easy_talk/builders/base_builder.rb

Overview

BaseBuilder is a class that provides a common structure for building schema properties

Constant Summary collapse

COMMON_OPTIONS =

BaseBuilder is a class that provides a common structure for building objects representing schema properties.

{
  title: { type: T.nilable(String), key: :title },
  description: { type: T.nilable(String), key: :description },
  optional: { type: T.nilable(T::Boolean), key: :optional }
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, schema, options = {}, valid_options = {}) ⇒ BaseBuilder

Initializes a new instance of the BaseBuilder class.

Parameters:

  • name (Symbol)

    The name of the property.

  • schema (Hash)

    A hash representing a json schema object.

  • options (Hash) (defaults to: {})

    The options for the builder (default: {}).

  • valid_options (Hash) (defaults to: {})

    The acceptable options for the given property type (default: {}).



34
35
36
37
38
39
40
# File 'lib/easy_talk/builders/base_builder.rb', line 34

def initialize(name, schema, options = {}, valid_options = {})
  @valid_options = COMMON_OPTIONS.merge(valid_options)
  options.assert_valid_keys(@valid_options.keys)
  @name = name
  @schema = schema
  @options = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



18
19
20
# File 'lib/easy_talk/builders/base_builder.rb', line 18

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



18
19
20
# File 'lib/easy_talk/builders/base_builder.rb', line 18

def options
  @options
end

#schemaObject (readonly)

Returns the value of attribute schema.



18
19
20
# File 'lib/easy_talk/builders/base_builder.rb', line 18

def schema
  @schema
end

Class Method Details

.collection_type?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/easy_talk/builders/base_builder.rb', line 58

def self.collection_type?
  false
end

Instance Method Details

#buildObject



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/easy_talk/builders/base_builder.rb', line 44

def build
  @valid_options.each_with_object(schema) do |(key, value), obj|
    next if @options[key].nil?

    # Work around for Sorbet's default inability to type check the items inside an array

    if value[:type].respond_to?(:recursively_valid?) && !value[:type].recursively_valid?(@options[key])
      raise TypeError, "Invalid type for #{key}"
    end

    obj[value[:key]] = T.let(@options[key], value[:type])
  end
end