Method: BBLib.const_create

Defined in:
lib/bblib/core/util/object.rb

.const_create(name, value, strict: true, base: Object, type_of_missing: nil, &block) ⇒ Object

Create a new class or module recursively within a provided namespace. If a constant matching the requested one already exist it is returned. Any block passed to this method will be evaled in the created/found constant.

Raises:

  • (TypeError)


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/bblib/core/util/object.rb', line 90

def self.const_create(name, value, strict: true, base: Object, type_of_missing: nil, &block)
  namespace = base
  unless base.const_defined?(name)
    type_of_missing = Module unless type_of_missing
    name = name.uncapsulate('::')
    if name.include?('::')
      namespaces = name.split('::')
      name = namespaces.pop
      namespaces.each do |constant|
        unless namespace.const_defined?(constant)
          match = namespace.const_set(constant, type_of_missing.new)
        end
        namespace = namespace.const_get(constant)
      end
    end
    namespace.const_set(name, value)
  end
  object = namespace.const_get(name)
  raise TypeError, "Expected a #{value.class} but #{namespace}::#{name} is a #{object.class}" if strict && object.class != value.class
  object.tap do |constant|
    constant.send(:class_exec, &block) if block
  end
end