Dynamically load a class in ruby example

Thursday, July 30, 2009

Dynamically loading a ruby class or ruby module is arguably, one of the most powerful feature, Ruby language has. Below example demonstrates its usage, you can also refer to rdoc for more information.
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

Object.const_get("String") # -> String
Object.const_get(:String) # -> String

require 'test/unit'
Test.deep_const_get("Unit::Assertions") # -> Test::Unit::Assertions
Test.deep_const_get("::Test::Unit") # -> Test::Unit

0 comments: