Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active December 16, 2015 02:19
Show Gist options
  • Save jgaskins/5361185 to your computer and use it in GitHub Desktop.
Save jgaskins/5361185 to your computer and use it in GitHub Desktop.
Temporarily reassigning a constant
module A
module B
C = Class.new
end
end
def redefine_constant full_const_name, value
const_path = full_const_name.to_s.split('::')
namespace = const_path[0..-2].inject(Kernel) { |scope, name| scope.const_get(name) }
const = const_path[-1]
orig_value = namespace.const_get(const)
namespace.send :remove_const, const
namespace.const_set(const, value)
yield
namespace.send :remove_const, const
namespace.const_set(const, orig_value)
end
describe 'redefining constants' do
it 'redefines a nested constant' do
orig_value = A::B::C
new_value = double('New Value')
redefine_constant(A::B::C, new_value) do
A::B::C.should be new_value
end
A::B::C.should be orig_value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment