Skip to content

Instantly share code, notes, and snippets.

@shipstar
Last active December 14, 2015 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shipstar/5016267 to your computer and use it in GitHub Desktop.
Save shipstar/5016267 to your computer and use it in GitHub Desktop.
when_constant
# usage:
# when_constant "Foo::BAR", 'baz' do
# # do something
# end
def when_constant(constant_string, new_value)
class_or_module = nil
constant_name = nil
if constant_string =~ /::/
values = constant_string.split("::")
class_or_module = values[0..-2].join("::").constantize
constant_name = values[-1]
else
class_or_module = Object
constant_name = constant_string
end
old_value = class_or_module.const_get constant_name
class_or_module.send(:remove_const, constant_name)
class_or_module.const_set constant_name, new_value
yield
class_or_module.send(:remove_const, constant_name)
class_or_module.const_set constant_name, new_value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment