class Pico::Autoloader

Attributes

base_nibbles[RW]

Public Class Methods

new(from) click to toggle source
# File lib/pico/autoloader.rb, line 7
def initialize(from)
  @from = from
  @context, @base_nibbles = fetch_context_and_base_nibbles
  @dir_paths = [nil]
end

Public Instance Methods

<<(const_name) click to toggle source
# File lib/pico/autoloader.rb, line 13
def <<(const_name)
  raise_name_error!(const_name) unless context
  @dir_paths = each_possible_const(const_name).reduce [] do |new_paths, possible_const|
    resolved_const = context.resolve_const possible_const
    throw :const, resolved_const if resolved_const
    new_paths << possible_const if dir?(possible_const)
    new_paths
  end
  raise_name_error!(const_name) if dir_paths.empty?
end
constify(*nibbles) click to toggle source
# File lib/pico/autoloader.rb, line 36
def constify(*nibbles)
  nibbles.compact.join '::'
end
dir?(possible_const) click to toggle source
# File lib/pico/autoloader.rb, line 32
def dir?(possible_const)
  context.possible_implicit_namespace? possible_const.to_snake_case
end
each_base_nibble() { |mod, const| ... } click to toggle source

given “Foo::Bar::Baz”, return [“Foo”, “Bar”, “Baz”]

# File lib/pico/autoloader.rb, line 58
def each_base_nibble
  return to_enum(:each_base_nibble) unless block_given?
  from.name.split('::').reduce Object do |mod, const|
    mod = mod.const_get const
    yield [mod, const]
    mod
  end
end
each_possible_const(const_name) { |constify(e, *dir_path, const_name)| ... } click to toggle source
# File lib/pico/autoloader.rb, line 24
def each_possible_const(const_name)
  return to_enum(:each_possible_const, const_name) unless block_given?
  dir_paths.each do |dir_path|
    base_nibbles.map { |e| yield constify(e, *dir_path, const_name) }
    yield constify(*dir_path, const_name)
  end
end
fetch_context_and_base_nibbles() click to toggle source

given “Foo::Bar::Baz”, return [“Foo::Bar::Baz”, “Foo::Bar”, etc.]

# File lib/pico/autoloader.rb, line 47
def fetch_context_and_base_nibbles
  each_base_nibble.to_a.reverse.reduce [] do |ary, (mod, const)|
    owner = Pico.contexts.each_value.detect { |c| c.mod == mod }
    return [owner, ary] if owner
    ary.map! do |e| e.insert 0, '::'; e.insert 0, const; end
    ary << const
  end
  nil
end
raise_name_error!(const_name = dir_paths.last) click to toggle source
# File lib/pico/autoloader.rb, line 40
def raise_name_error!(const_name = dir_paths.last)
  message = "uninitialized constant #{const_name}"
  message << " (in #{context.mod})" if context
  raise NameError, message
end