Skip to content

Instantly share code, notes, and snippets.

@denyago
Created April 25, 2013 13:27
Show Gist options
  • Save denyago/5459671 to your computer and use it in GitHub Desktop.
Save denyago/5459671 to your computer and use it in GitHub Desktop.
Unset Ruby constant
##
# Unsets constant `const_name` from all available Modules.
# Will not do anything, if constant not constantizable.
#
# Params:
# - const_name {Symbol} or {String} name of constant,
# able to be constantized
#
# Returns {Boolean} as a result of unsetting
def unset_const!(const_name)
return false unless const_name.to_s.safe_constantize
const_name = const_name.to_sym
const_owners = Module.constants.select do |c|
c.to_s.constantize.
constants(false).include?(const_name) rescue false
end
const_owners.each do |owner|
puts "#{owner} defines #{const_name}, unsetting."
owner.to_s.constantize.send(:remove_const, const_name)
end
true
end
describe 'unsets any constant from all owners' do
before do
module Rails; end
end
it 'returns if constant not present' do
subject.unset_const!(:FooBar).should be_false
end
context 'with single owner' do
it "by finding it's owner" do
subject.unset_const!(:Rails)
defined?(Rails).should_not eq 'constant'
end
end
context 'with multiple owners' do
before do
module Dummy
module Rails; end
end
end
it "by finding it's multiple owners" do
subject.unset_const!('Rails')
defined?(Rails).should_not eq 'constant'
end
after do
Dummy.send(:remove_const, :Rails) if defined?(::Dummy::Rails)
Object.send(:remove_const, :Dummy) if defined?(::Dummy)
end
end
after do
Object.send(:remove_const, :Rails) if defined?(::Rails)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment