Class: Rns::Namespace

Inherits:
Object
  • Object
show all
Defined in:
lib/rns.rb

Overview

An internal class used to support Kernel#Rns in returning namespaces

Class Method Summary collapse

Class Method Details

.import(imports) ⇒ Object

Imports methods from objects into this namespace class as private instance methods.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rns.rb', line 41

def import(imports)
  ns_methods = instance_methods.map(&:to_sym)
  @_import_hash = array_to_key_value_tuples(imports).reduce({}) do |h, (obj, methods)|
    if !obj.frozen?
      raise ImportError, "#{obj} cannot be imported into Namespace because it is not frozen"
    elsif !obj.class.frozen?
      raise ImportError, "#{obj} cannot be imported into Namespace because its class is not frozen"
    end

    (methods || obj.public_methods(false)).each do |method|
      if ns_methods.include? method
        raise ImportError, "cannot override #{method} with an import"
      end
      h[method.to_sym] = obj.method(method)
    end

    h
  end

  file, line = import_call_site(caller)
  @_import_hash.each do |method, _|
    # eval is needed because:
    #   * Module#define_method can't delegate to methods that accept blocks
    #   * method_missing can, but then imported methods are available publicly
    module_eval(delegate_to_hash_source(method, :@_import_hash), file, line - 1)
    private method
  end
end