Skip to content

Instantly share code, notes, and snippets.

@kpumuk
Created December 2, 2008 13:09
Show Gist options
  • Save kpumuk/31109 to your computer and use it in GitHub Desktop.
Save kpumuk/31109 to your computer and use it in GitHub Desktop.
# 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