Created
December 2, 2008 13:09
-
-
Save kpumuk/31109 to your computer and use it in GitHub Desktop.
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
# Redefines const value during block execution. | |
# | |
# Usage example: | |
# SOMECONST = 1 # SOMECONST == 1 | |
# redefine_const(:SOMECONST, 'hello') do | |
# puts SOMECONST # SOMECONST == 'hello' | |
# end | |
# # SOMECONST == 1 | |
def redefine_const(const, value, &block) | |
if const_defined = Object.const_defined?(const) | |
old_value = Object.const_get(const) | |
Object.send(:remove_const, const) | |
end | |
Object.const_set(const, value) | |
yield | |
ensure | |
Object.send(:remove_const, const) | |
Object.const_set(const, old_value) if const_defined | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment