Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Created September 9, 2011 07:06
Show Gist options
  • Save a2ikm/1205652 to your computer and use it in GitHub Desktop.
Save a2ikm/1205652 to your computer and use it in GitHub Desktop.
Get or set nested constant
#!/usr/bin/ruby
class Object
# copied from http://blog.udzura.jp/2010/03/08/petit-hacking-about-const_get/
def self.nested_const_get(name)
stack = (name.is_a?(Array)) ? name : name.to_s.split("::")
klass = Object
while const = stack.shift
klass = klass.const_get(const)
end
return klass
end
def self.nested_const_set(args = {})
args.each do |name, value|
stack = (name.is_a?(Array)) ? name : name.to_s.split("::")
last_const = stack.pop
klass = nested_const_get(stack)
klass.const_set(last_const, value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment