File: to_const.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (31 lines) | stat: -rw-r--r-- 607 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class String

  # Get a constant by a given string name.
  #
  #   "Class".to_const   #=> Class
  #
  # Note this method is not as verstile as it should be,
  # since it can not access contants relative to the current
  # execution context. But without a binding_of_caller that
  # does not seem possible.

  def to_const
    split('::').inject(Object){ |namespace,name| namespace.const_get(name) }
  end

end


__END__

require 'test/unit'

class TestStringConversion < Test::Unit::TestCase

  TestConst = 4

  def test_to_const
    assert_equal( 4, "TestStringConversion::TestConst".to_const )
  end

end