Sha256: 86f02e94e0e466c818b7165053cf4ee8180eb95cfe4ef47c84b09eb7efd1b144
Contents?: true
Size: 1.68 KB
Versions: 22
Compression:
Stored size: 1.68 KB
Contents
require 'facet/kernel/constant' class Module # <em>Note: the following documentation uses "class" because it's more common, but it # applies to modules as well.</em> # # Given the _name_ of a class, returns the class itself (i.e. instance of Class). The # dereferencing starts at Object. That is, # # Class.by_name("String") # # is equivalent to # # Object.const_get("String") # # The parameter _name_ is expected to be a Symbol or String, or at least to respond to # <tt>to_str</tt>. # # An ArgumentError is raised if _name_ does not correspond to an existing class. If _name_ # is not even a valid class name, the error you'll get is not defined. # # Examples: # # Class.by_name("String") # -> String # Class.by_name("::String") # -> String # Class.by_name("Process::Sys") # -> Process::Sys # Class.by_name("GorillaZ") # -> (ArgumentError) # # Class.by_name("Enumerable") # -> Enumerable # Module.by_name("Enumerable") # -> Enumerable # #-- # Credit for this goes to Gavin Sinclair #++ def by_name(name) result = Object.constant(name) return result if result.kind_of?( Module ) raise ArgumentError, "#{name} is not a module or class" end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCModule < Test::Unit::TestCase def test_by_name c = ::Test::Unit::TestCase.name assert_equal( ::Test::Unit::TestCase, Module.by_name(c) ) c = "Test::Unit::TestCase" assert_equal( ::Test::Unit::TestCase, Class.by_name(c) ) end end =end
Version data entries
22 entries across 22 versions & 1 rubygems