aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/class/removal.rb
blob: 80a920e4d6cfdf95d594359fa27e086f6d349c41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'active_support/core_ext/object/extending'
require 'active_support/core_ext/module/introspection'

class Class #:nodoc:
  # Removes the classes in +klasses+ from their parent module.
  #
  # Ordinary classes belong to some module via a constant. This method computes
  # that constant name from the class name and removes it from the module it
  # belongs to.
  #
  #   Object.remove_class(Integer) # => [Integer]
  #   Integer                      # => NameError: uninitialized constant Integer
  #
  # Take into account that in general the class object could be still stored
  # somewhere else.
  #
  #   i = Integer                  # => Integer
  #   Object.remove_class(Integer) # => [Integer]
  #   Integer                      # => NameError: uninitialized constant Integer
  #   i.subclasses                 # => ["Bignum", "Fixnum"]
  #   Fixnum.superclass            # => Integer
  def remove_class(*klasses)
    klasses.flatten.each do |klass|
      # Skip this class if there is nothing bound to this name
      next unless defined?(klass.name)
      
      basename = klass.to_s.split("::").last
      parent = klass.parent
      
      # Skip this class if it does not match the current one bound to this name
      next unless parent.const_defined?(basename) && klass = parent.const_get(basename)

      parent.instance_eval { remove_const basename } unless parent == klass
    end
  end
end