Skip to content

Instantly share code, notes, and snippets.

@ajokela
Forked from anonymous/gist:5490823
Created April 30, 2013 20:10
Show Gist options
  • Save ajokela/5491557 to your computer and use it in GitHub Desktop.
Save ajokela/5491557 to your computer and use it in GitHub Desktop.
Module#recursive_const_get
class Module
def recursive_const_get(name)
name.to_s.split("::").inject(self) do |b, c|
b.const_get(c)
end
end
end
#Example
module Foo
BAR = "Hello World!"
end
Module.const_get("Foo::BAR") rescue $!
# => #<NameError: wrong constant name Foo::BAR>
Module.const_get("Foo").const_get("BAR")
# => "Hello World!"
Module.recursive_const_get("Foo::BAR")
# => "Hello World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment