Module: Eco::Language::Klass::Builder

Includes:
Naming, Resolver, Uid
Included in:
HelpersBuilt
Defined in:
lib/eco/language/klass/builder.rb

Instance Method Summary collapse

Methods included from Uid

#uid

Methods included from Naming

#instance_variable_name, #to_constant

Methods included from Resolver

#class_resolver, #resolve_class

Instance Method Details

#new_class(name = "Child#{uid}", inherits: self, namespace: inherits) {|child_class| ... } ⇒ Class

If the class for name exists, it returns it. Otherwise it generates it.

Parameters:

  • name (String, Symbol) (defaults to: "Child#{uid}")

    the name of the new class

  • inherits (Class) (defaults to: self)

    the parent class to inherit from

  • namespace (Class, String) (defaults to: inherits)

    an existing constant (class or module) the new class will be namespaced on

Yields:

  • (child_class)

    configure the new class

Yield Parameters:

  • child_class (Class)

    the new class

Returns:

  • (Class)

    the new generated class



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/eco/language/klass/builder.rb', line 14

def new_class(name = "Child#{uid}", inherits: self, namespace: inherits)
  name            = name.to_s.to_sym.freeze
  class_name      = to_constant(name)
  full_class_name = "#{namespace}::#{class_name}"

  unless (target_class = resolve_class(full_class_name, exception: false))
    target_class = Class.new(inherits)
    Kernel.const_get(namespace.to_s).const_set class_name, target_class
  end

  target_class.tap do |klass|
    yield(klass) if block_given?
  end
end