aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2005-01-25 17:55:55 +0000
committerDavid Heinemeier Hansson <david@loudthinking.com>2005-01-25 17:55:55 +0000
commitc37e8d365b9470a593668476fc9be0af6da2e812 (patch)
tree7374ddad0771220e85c63afd8f0a83bf2e59716a
parent136962322b8da0d6c09b4962194216cc4d248130 (diff)
downloadrails-c37e8d365b9470a593668476fc9be0af6da2e812.tar.gz
rails-c37e8d365b9470a593668476fc9be0af6da2e812.tar.bz2
rails-c37e8d365b9470a593668476fc9be0af6da2e812.zip
Added methods for removing subclasses -- couldnt make it work with the regular nested-module approach (ObjectSpace was being difficult), so this is a straight inclusion
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@506 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
-rw-r--r--activesupport/lib/core_ext/object_and_class.rb24
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb21
2 files changed, 45 insertions, 0 deletions
diff --git a/activesupport/lib/core_ext/object_and_class.rb b/activesupport/lib/core_ext/object_and_class.rb
new file mode 100644
index 0000000000..59a463ae29
--- /dev/null
+++ b/activesupport/lib/core_ext/object_and_class.rb
@@ -0,0 +1,24 @@
+class Object #:nodoc:
+ def remove_subclasses_of(superclass)
+ subclasses_of(superclass).each { |subclass| Object.send(:remove_const, subclass) rescue nil }
+ end
+
+ def subclasses_of(superclass)
+ subclasses = []
+ ObjectSpace.each_object(Class) do |k|
+ next if !k.ancestors.include?(superclass) || superclass == k || k.to_s.include?("::") || subclasses.include?(k.to_s)
+ subclasses << k.to_s
+ end
+ subclasses
+ end
+end
+
+class Class #:nodoc:
+ def remove_subclasses
+ Object.remove_subclasses_of(self)
+ end
+
+ def subclasses
+ Object.subclasses_of(self)
+ end
+end
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
new file mode 100644
index 0000000000..5a0ae58837
--- /dev/null
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -0,0 +1,21 @@
+require 'test/unit'
+require File.dirname(__FILE__) + '/../../lib/core_ext/object_and_class'
+
+class A; end
+class B < A; end
+class C < B; end
+class D < A; end
+
+class ClassExtTest < Test::Unit::TestCase
+ def test_methods
+ assert defined?(B)
+ assert defined?(C)
+ assert defined?(D)
+
+ A.remove_subclasses
+
+ assert !defined?(B)
+ assert !defined?(C)
+ assert !defined?(D)
+ end
+end