module Kernel # This is similar to +Module#const_get+ but is accessible at all levels, # and, unlike +const_get+, can handle module hierarchy. # # constant("Fixnum") # -> Fixnum # constant(:Fixnum) # -> Fixnum # # constant("Process::Sys") # -> Process::Sys # constant("Regexp::MULTILINE") # -> 4 # # require 'test/unit' # Test.constant("Unit::Assertions") # -> Test::Unit::Assertions # Test.constant("::Test::Unit") # -> Test::Unit # def constant(const) const = const.to_s.dup base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class ) const.split(/::/).inject(base){ |mod, name| mod.const_get(name) } end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCKernel < Test::Unit::TestCase def test_constant c = ::Test::Unit::TestCase.name assert_equal( ::Test::Unit::TestCase, constant(c) ) c = "Test::Unit::TestCase" assert_equal( ::Test::Unit::TestCase, constant(c) ) c = "Unit::TestCase" assert_equal( ::Test::Unit::TestCase, Test.constant(c) ) c = "TestCase" assert_equal( ::Test::Unit::TestCase, Test::Unit.constant(c) ) end end =end