class Dry::Struct::StructBuilder

@private

Attributes

struct[R]

Public Class Methods

new(struct) click to toggle source
Calls superclass method
# File lib/dry/struct/struct_builder.rb, line 11
def initialize(struct)
  super(Types)
  @struct = struct
end

Public Instance Methods

call(attr_name, type, &block) click to toggle source

@param [Symbol|String] attr_name the name of the nested type @param [Dry::Struct,Dry::Types::Type::Array,Undefined] type the superclass of the nested struct @yield the body of the nested struct

# File lib/dry/struct/struct_builder.rb, line 19
def call(attr_name, type, &block)
  const_name = const_name(type, attr_name)
  check_name(const_name)

  builder = self
  parent = parent(type)

  new_type = ::Class.new(Undefined.default(parent, struct.abstract_class)) do
    if Undefined.equal?(parent)
      schema builder.struct.schema.clear
    end

    class_exec(&block)
  end

  struct.const_set(const_name, new_type)

  if array?(type)
    type.of(new_type)
  elsif optional?(type)
    new_type.optional
  else
    new_type
  end
end

Private Instance Methods

array?(type) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 51
def array?(type)
  type?(type) && !type.optional? && type.primitive.equal?(::Array)
end
check_name(name) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 80
def check_name(name)
  if struct.const_defined?(name, false)
    raise(
      Error,
      "Can't create nested attribute - `#{struct}::#{name}` already defined"
    )
  end
end
const_name(type, attr_name) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 69
def const_name(type, attr_name)
  snake_name =
    if array?(type)
      Core::Inflector.singularize(attr_name)
    else
      attr_name
    end

  Core::Inflector.camelize(snake_name)
end
optional?(type) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 55
def optional?(type)
  type?(type) && type.optional?
end
parent(type) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 59
def parent(type)
  if array?(type)
    visit(type.to_ast)
  elsif optional?(type)
    type.right
  else
    type
  end
end
type?(type) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 47
def type?(type)
  type.is_a?(Types::Type)
end
visit_array(node) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 94
def visit_array(node)
  member, * = node
  visit(member)
end
visit_constrained(node) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 89
def visit_constrained(node)
  definition, * = node
  visit(definition)
end
visit_constructor(node) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 103
def visit_constructor(node)
  definition, * = node
  visit(definition)
end
visit_nominal(*) click to toggle source
# File lib/dry/struct/struct_builder.rb, line 99
def visit_nominal(*)
  Undefined
end