Class: Dry::Core::ClassBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/core/class_builder.rb

Overview

Class for generating more classes

Constant Summary collapse

ParentClassMismatch =
Class.new(TypeError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, parent: nil, namespace: nil) ⇒ ClassBuilder

Returns a new instance of ClassBuilder.



11
12
13
14
15
# File 'lib/dry/core/class_builder.rb', line 11

def initialize(name:, parent: nil, namespace: nil)
  @name = name
  @namespace = namespace
  @parent = parent || Object
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/dry/core/class_builder.rb', line 9

def name
  @name
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



9
10
11
# File 'lib/dry/core/class_builder.rb', line 9

def namespace
  @namespace
end

#parentObject (readonly)

Returns the value of attribute parent.



9
10
11
# File 'lib/dry/core/class_builder.rb', line 9

def parent
  @parent
end

Instance Method Details

#call {|klass| ... } ⇒ Class

Generate a class based on options

Examples:

Create anonymous class

builder = Dry::Core::ClassBuilder.new(name: 'MyClass')

klass = builder.call
klass.name # => "MyClass"

Create named class

builder = Dry::Core::ClassBuilder.new(name: 'User', namespace: Entities)

klass = builder.call
klass.name # => "Entities::User"
klass.superclass.name # => "Entities::User"
Entities::User # => "Entities::User"
klass.superclass == Entities::User # => true

Yields:

  • (klass)

Returns:

  • (Class)


35
36
37
38
39
40
41
42
43
44
45
# File 'lib/dry/core/class_builder.rb', line 35

def call
  klass = if namespace
            create_named
          else
            create_anonymous
          end

  yield(klass) if block_given?

  klass
end