Module: Constant::Import

Defined in:
lib/constant/import.rb,
lib/constant/import/macro.rb

Class Method Summary collapse

Class Method Details

.call(origin_constant, destination_constant, **kwargs) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/constant/import.rb', line 19

def self.call(origin_constant, destination_constant, **kwargs)
  if not destination_constant.is_a?(::Module)
    destination_constant = destination_constant.class
  end

  alias_name = kwargs[:alias]

  if alias_name.nil? && destination_constant.ancestors.include?(origin_constant)
    raise Constant::Error, "#{destination_constant} already includes #{origin_constant}"
  end

  target = destination_constant

  if not alias_name.nil?
    target = Define.(alias_name, destination_constant)
  end

  inherit = false

  import_constant_names = origin_constant.constants(inherit)

  imported_constants = import_constant_names.map do |import_constant_name|
    import_constant = origin_constant.const_get(import_constant_name, inherit)
    target.const_set(import_constant_name, import_constant)
    import_constant
  end

  imported_constants
end

.included(base) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/constant/import.rb', line 3

def self.included(base)
  if base.equal?(::Object)
    raise Constant::Error, "Constant::Import cannot be included at the top level, where the destination is Object. Activate the refinement instead: using Constant::Import"
  end

  base.extend(Macro)
end