Henning Kilset Pedersen
2006-Jan-05 10:34 UTC
[Rails] Looping through all models in the application
Hello. I have an application that depends on a table/model (ModelInternationalization) that provides international translations in various languages for all the model/table and columns names as well as some other stuff (whether the column is visible on forms, dropdowns, lists, reports etc). I need to create a management interface for this translation stuff (the plaintext stuff, btw, will be handled by GetText). To do this, I need to loop through all the models in the application and check if they are present for the currently selected language in the translation model. Maybe some pseudocode would help clarify for m in Application models <%= h m.model.name %> end Essentially, this would loop through all the models available to the application and just display it''s name. Ofcourse, the actually code is much more complex. Is there a collection of the available models somewhere? Or do I need to goof it up and just parse the directory listing of the app/models directory? Or worse, create a table with just the names of the models and loop through that? Regards, Henning Pedersen
On 1/5/06, Henning Kilset Pedersen <henning@mopo.no> wrote:> Hello. > > I have an application that depends on a table/model > (ModelInternationalization) that provides international translations in > various languages for all the model/table and columns names as well as > some other stuff (whether the column is visible on forms, dropdowns, > lists, reports etc). > > I need to create a management interface for this translation stuff (the > plaintext stuff, btw, will be handled by GetText). To do this, I need to > loop through all the models in the application and check if they are > present for the currently selected language in the translation model. > Maybe some pseudocode would help clarify > > for m in Application models > <%= h m.model.name %> > end > > Essentially, this would loop through all the models available to the > application and just display it''s name. Ofcourse, the actually code is > much more complex. > > Is there a collection of the available models somewhere? Or do I need to > goof it up and just parse the directory listing of the app/models > directory? Or worse, create a table with just the names of the models > and loop through that?This is really ugly, but this will give you a list of all objects that subclass from ActiveRecord::Base (which are all your models): ObjectSpace.each_object do |object| if object.class == Class and object.superclass == ActiveRecord::Base puts object.to_s end end You''ll probably need to skip CGI::Session::ActiveRecordStore::Session if you use ActiveRecordStore for your sessions. - Jamie