Skip to content

Instantly share code, notes, and snippets.

@dougo-chris
Created February 5, 2016 04:57
Show Gist options
  • Save dougo-chris/1e515f8175af257f1fcc to your computer and use it in GitHub Desktop.
Save dougo-chris/1e515f8175af257f1fcc to your computer and use it in GitHub Desktop.
# see http://stackoverflow.com/questions/1698335/can-i-use-rspec-mocks-to-stub-out-version-constants
class Object
def self.with_constants(constants, &block)
saved_constants = {}
constants.each do |constant, val|
saved_constants[ constant ] = const_get( constant )
Kernel::silence_warnings { const_set( constant, val ) }
end
begin
block.call
ensure
constants.each do |constant, val|
Kernel::silence_warnings { const_set( constant, saved_constants[ constant ] ) }
end
end
end
end
class Module
def with_constants(constants, &block)
saved_constants = {}
constants.each do |constant, val|
saved_constants[ constant ] = const_get( constant )
Kernel::silence_warnings { const_set( constant, val ) }
end
begin
block.call
ensure
constants.each do |constant, val|
Kernel::silence_warnings { const_set( constant, saved_constants[ constant ] ) }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment