Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.79 KB | None | 0 0
  1. module Kernel #:nodoc:
  2.  
  3.   # This is similar to +Module#const_get+ but is accessible at all levels,
  4.   # and, unlike +const_get+, can handle module hierarchy.
  5.   #
  6.   #   constant("Fixnum")                  # -> Fixnum
  7.   #   constant(:Fixnum)                   # -> Fixnum
  8.   #
  9.   #   constant("Process::Sys")            # -> Process::Sys
  10.   #   constant("Regexp::MULTILINE")       # -> 4
  11.   #
  12.   #   require 'test/unit'
  13.   #   Test.constant("Unit::Assertions")   # -> Test::Unit::Assertions
  14.   #   Test.constant("::Test::Unit")       # -> Test::Unit
  15.   #
  16.   # CREDIT: Trans
  17.  
  18.   def constant(const)
  19.     const = const.to_s.dup
  20.     base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class )
  21.     const.split(/::/).inject(base){ |mod, name| mod.const_get(name) }
  22.   end
  23.  
  24. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement