#!/usr/bin/ruby -w

class String
  # 
  # Return a reference to a class or module named in a String object
  # 
  # Description:
  #   Return a reference to a class or module named in a String object.
  #   You can specify a non-Kernel top-level namespace by passing it as
  #   a parameter.  Returns nil if the String object is empty or if it
  #   does not contain a valid class or module name.
  # 
  # Aliases:
  #   String#to_c
  #
  # Examples:
  #   # standard use
  #   image_class = 'Imlib2::Image'.to_class
  #   image = image_class.new(640, 480)
  #
  #   # non-standard base namespace
  #   image_class = 'Image'.to_class(Imlib2)
  #   image = image_class.new(640, 480)
  #   
  def to_class(base_class = Kernel)
    begin 
      path = self.gsub(/::/, '.').split(/\./)
      c = base_class::const_get path.shift
      path.each { |i| c = c::const_get i } if path
      c
    rescue Exception
      nil
    end
  end

  alias_method :to_c, :to_class
end

# test String#to_class
if __FILE__ == $0
  class_path, require_string = ARGV

  # if nothign was specified on the command line, then default to
  # Net::HTTP, and require the net/http module
  unless class_path
    class_path = 'Net::HTTP'
    require_string = 'net/http'
  end

  # require a module if one was specified on the command line
  require require_string if require_string

  # do our testing
  c_id = 0; eval "c_id = #{class_path}.id" if class_path
  c = class_path.to_c
  puts "c.id = #{c.id}",
       "#{class_path}.id = #{c_id}"
end

