Listing subclasses not working in Ruby script / console?

It works:

>> class Foo >> def xyz() >> Foo.subclasses >> end >> end => nil >> class Bar < Foo >> end => nil >> class Quux < Bar >> end => nil >> Foo.new.xyz() => ["Quux", "Bar"] 

But this is not so. User is the class in my application.

 >> User.subclasses NoMethodError: protected method `subclasses' called for #<Class:0x20b5188> from [...]/vendor/rails/activerecord/lib/active_record/base.rb:1546:in `method_missing' from (irb):13 

But it is so!

 >> Foo.subclasses => ["Quux", "Bar"] 

What's going on here? How can I list subclasses of User ?

+1
source share
4 answers
Subclasses

redefined and protected in base.rb. See http://www.google.com/codesearch/p?hl=en&sa=N&cd=1&ct=rc#m8Vht-lU3vE/vendor/rails/activerecord/lib/active_record/base.rb&q=active_record/base.rb ( line 1855 defines subclasses of methods, line 1757 protects them).

You can do the same for the user as for Foo: add the xyz () method.

+2
source

You do not need to update (as in Tim's answer ) or provide a helper method (as in Rutger's answer ). You just need to change the resolution of the method (which, being a class method, requires some fraud):

 class User < ActiveRecord::Base class <<self public :subclasses end end 
+1
source

To bypass access rights and not change anything, consider using the #send method, which has access to private methods.

 User.send(:subclasses) 
+1
source
 tables = ActiveRecord::Base.connection.tables {|t| t.classify.constantize rescue nil}.compact subclasses = tables.map do |table| table.singularize.classify.constantize end 
0
source

All Articles