Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list/array of child classes from Single Table Inheritance in Rails?

I have a whole bunch of child classes that inherit from a parent class via single-table-inheritance in my Rails app. I'd like a way to get an array of all the child classes that inherit from the main class.

I tried the following single-link command that I found in another SO answer, but it only returns the parent class.

ObjectSpace.each_object(class<<MyParentClass;self;end)

Is there any clean way to do this?

EDIT: Apparently Rails only lazy-loads child classes when called in Dev mode, and possibly production depending on the Rails version. However, the first answer should work on Rails 3.1 and higher in Prod mode.

like image 568
thoughtpunch Avatar asked May 10 '12 13:05

thoughtpunch


3 Answers

Rails extends Ruby Class with the subclasses() method.

In Rails 3 you can call it directly:

YourClass.subclasses

In Rails 2.3, ".subclasses" is protected, so we use have to call it using send():

YourClass.send(:subclasses)
like image 117
Pavling Avatar answered Oct 14 '22 10:10

Pavling


You need to eager load the classes, as stated in: https://github.com/rails/rails/issues/3364

ActionDispatch::Reloader.to_prepare do
  Rails.application.eager_load!
end

Then you will be able to use:

YourClass.subclasses

or

YourClass.descendants
like image 28
sequielo Avatar answered Oct 14 '22 10:10

sequielo


ParentClass.subclasses.map(&:name)
like image 6
Adam Avatar answered Oct 14 '22 11:10

Adam