Module: ImportConstants

Defined in:
lib/import_constants/macro.rb,
lib/import_constants/import_constants.rb,
lib/import_constants/controls/namespace.rb

Defined Under Namespace

Modules: Controls, Macro

Constant Summary collapse

Error =
Class.new(RuntimeError)

Class Method Summary collapse

Class Method Details

.call(source_namespace, target_namespace = nil, as: nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/import_constants/import_constants.rb', line 8

def self.call(source_namespace, target_namespace=nil, as: nil)
  target_namespace ||= Object
  alias_name = as

  if not alias_name.nil?
    if target_namespace.const_defined?(alias_name, false)
      raise Error, "#{target_namespace}::#{alias_name} is already defined"
    end

    alias_module = Module.new
    ImportConstants.(source_namespace, alias_module)

    target_namespace.const_set(alias_name, alias_module)

  else
    inherit = false
    constants = source_namespace.constants(inherit)

    constants.each do |constant_name|
      constant = source_namespace.const_get(constant_name)

      if target_namespace.const_defined?(constant_name, false)
        if warn?
          warn "#{source_namespace}::#{constant_name} is not imported into #{target_namespace}. It is already defined."
        end
        next
      end

      target_namespace.const_set(constant_name, constant)
    end
  end
end

.included(target_namespace) ⇒ Object



4
5
6
# File 'lib/import_constants/import_constants.rb', line 4

def self.included(target_namespace)
  target_namespace.extend(Macro)
end

.warn?Boolean



41
42
43
# File 'lib/import_constants/import_constants.rb', line 41

def self.warn?
  ENV.fetch('IMPORT_CONSTANTS_WARNING', 'on') == 'on'
end