Last active
December 14, 2015 02:49
-
-
Save shipstar/5016267 to your computer and use it in GitHub Desktop.
when_constant
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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