Module: Package::KernelMethods

Defined in:
lib/package.rb

Constant Summary collapse

NS_SEP =
'/'.freeze

Class Method Summary collapse

Class Method Details

.import(caller_binding, namespace, as: nil, to: :method) ⇒ Object

Return the package as a value



10
11
12
13
14
# File 'lib/package.rb', line 10

def import(caller_binding, namespace, as: nil, to: :method)
  to ||= :value

  send("import_to_#{to}", caller_binding, namespace, as: as)
end

.import_to_const(caller_binding, namespace, as: nil) ⇒ Object

Set a const to the package in the caller’s context Return the package as a value



50
51
52
53
54
55
56
57
58
59
# File 'lib/package.rb', line 50

def import_to_const(caller_binding, namespace, as: nil)
  sym = (as || ns_classify(ns_last(namespace)).to_sym)
  clr = caller_binding.eval('self')
  target = clr.respond_to?(:const_set) ? clr : clr.class
  setter = target.instance_eval(<<-RUBY, __FILE__, __LINE__ + 1)
    -> (v) { const_set(:#{sym}, v) }
  RUBY

  setter.call(Package.new(namespace))
end

.import_to_local(caller_binding, namespace, as: nil) ⇒ Object

Assign the package to a local variable in the caller’s binding Return the package as a value /!\ Experimental



26
27
28
29
30
31
32
33
34
# File 'lib/package.rb', line 26

def import_to_local(caller_binding, namespace, as: nil)
  sym = (as || ns_last(namespace)).to_sym
  setter = caller_binding.eval(<<-RUBY)
    #{sym} = nil
    -> (v) { #{sym} = v }
  RUBY

  setter.call(Package.new(namespace))
end

.import_to_method(caller_binding, namespace, as: nil) ⇒ Object

Define a method in the caller’s context that hands out the package Return the package as a value



38
39
40
41
42
43
44
45
46
# File 'lib/package.rb', line 38

def import_to_method(caller_binding, namespace, as: nil)
  sym = (as || ns_last(namespace)).to_sym
  clr = caller_binding.eval('self')
  setter = clr.instance_eval(<<-RUBY, __FILE__, __LINE__ + 1)
    -> (v) { define_singleton_method(:#{sym}) { v }; v }
  RUBY

  setter.call(Package.new(namespace))
end

.import_to_value(_binding, namespace, as: nil) ⇒ Object

Return the package as a value rubocop:disable Lint/UnusedMethodArgument



18
19
20
# File 'lib/package.rb', line 18

def import_to_value(_binding, namespace, as: nil)
  Package.new(namespace)
end

.ns_classify(namespace) ⇒ Object



73
74
75
76
77
# File 'lib/package.rb', line 73

def ns_classify(namespace)
  namespace.split(NS_SEP).map! do |v|
    v.split('_').map!(&:capitalize).join('')
  end.join('::')
end

.ns_from_filename(ns) ⇒ Object



61
62
63
# File 'lib/package.rb', line 61

def ns_from_filename(ns)
  ns.gsub('/', NS_SEP).gsub(/\.rb$/, '')
end

.ns_last(ns) ⇒ Object



69
70
71
# File 'lib/package.rb', line 69

def ns_last(ns)
  ns.split(NS_SEP).last
end

.ns_to_filename(ns) ⇒ Object



65
66
67
# File 'lib/package.rb', line 65

def ns_to_filename(ns)
  ns.gsub(NS_SEP, '/') + '.rb'
end