Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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