module Package::KernelMethods

Constants

NS_SEP

Public Instance Methods

import(caller_binding, namespace, as: nil, to: :method) click to toggle source

Return the package as a value

# 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) click to toggle source

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

# 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) click to toggle source

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

# 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) click to toggle source

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

# 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) click to toggle source

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

# File lib/package.rb, line 18
def import_to_value(_binding, namespace, as: nil)
  Package.new(namespace)
end
ns_classify(namespace) click to toggle source
# 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) click to toggle source
# File lib/package.rb, line 61
def ns_from_filename(ns)
  ns.gsub('/', NS_SEP).gsub(/\.rb$/, '')
end
ns_last(ns) click to toggle source
# File lib/package.rb, line 69
def ns_last(ns)
  ns.split(NS_SEP).last
end
ns_to_filename(ns) click to toggle source
# File lib/package.rb, line 65
def ns_to_filename(ns)
  ns.gsub(NS_SEP, '/') + '.rb'
end