Sha256: d4a41ecf1e4d3aae6f0b76aa5751fac6dde5c85afb83c1f5b27ab180ffa8e9d0

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

# Copyright: Copyright (c) 2004  Nicolas Despres. All rights reserved.
# Author: Nicolas Despres  <polrop@lrde.epita.fr>.
# License: Gnu General Public License.

# $LastChangedBy: ertai $
# $Id: autoload_tree.rb 217 2005-05-09 12:01:07Z ertai $


require 'pathname_ex'


class Module

  def autoload_tree(dir, recursive=true, &block)
    pdir = Pathname.new(dir)
    pdir.each_entry do |p|
      next if p.to_s =~ /^\./
      pfull = pdir + p
      if pfull.directory? and recursive
        name = p.to_s.capitalize!
        const_set(name, Module.new) unless const_defined?(name)
        const_get(name).autoload_tree(pfull, recursive, &block)
      elsif pfull.file? and p.to_s =~ /\.rb$/
        autoload(name.to_s, pfull.to_s) if name = block[p]
      end
    end
  end

  def autoloaded_module ( file )
    dir = file.sub(/\.rb$/, '').to_path
    autoload_tree(dir) do |path|
      path.basename.to_s.sub(/\.rb$/, '').gsub(/(?:^|_)([a-z])/) { $1.upcase }
    end
  end

end # class Module


if (not defined? AUTOLOAD_TREE_TESTED) and
    (defined? TEST_MODE or __FILE__ == $0)
AUTOLOAD_TREE_TESTED = true

require 'test/unit/ui/console/testrunner'


class AutoloadTreeTest < Test::Unit::TestCase

  if defined? SRC_DIR
    REPO_DIR = SRC_DIR + Pathname.new('../test/resources/autoload_tree')
  else
    REPO_DIR = Pathname.new(__FILE__).dirname +
               Pathname.new('../../test/resources/autoload_tree')
  end

  module AutoloadTree; end

  #
  # Test
  #
  def test_autoload_tree
    $: << REPO_DIR
    AutoloadTree.autoload_tree(REPO_DIR) { |p| p.to_s.sub!(/\.rb$/, '') }
    ["Foo", "B", "A"].each do |x|
      assert(AutoloadTree.constants.include?(x), "#{x} is missing")
    end
    assert_equal(["C"], AutoloadTree::Foo.constants)
    $:.delete(REPO_DIR)
  end

end # class AutoloadTreeTest


end


Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vcs-0.2.148 ruby_ex/module/autoload_tree.rb