Iterating over all Models in Rails 2

Posted by Matt on May 16, 2008

Neat little snippet of code in those odd times you need to loop over every model in your application programmatically.

This exact snippet loops over every model, and converts each timestamp (created_at, updated_at) to UTC. It can be quite helpful if you're adding Time Zone support to your Rails 2.1 application and you have existing non-UTC timestamps.

    all_models = Dir.glob( File.join( RAILS_ROOT, 'app', 'models', '*.rb') ).map{|path| path[/.+/(.+).rb/,1] }
    ar_models = all_models.select{|m| m.classify.constantize < ActiveRecord::Base}

*Please note: I haven't tested this very thoroughly, but it does seem to do the trick. As we know, Dates and Times can be total PITAs!

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Mike Mayo Sat, 05 Jul 2008 02:13:33 PDT

    Matt, I was about to write this exact same utility so I could add time zone support to my site, and I see you’ve already done it! Thanks, this is great!

  2. bryan Wed, 06 Aug 2008 18:37:59 PDT

    Hey Matt,

    Tried your snip and it seems to only dump cached models.

    # bw: hijacked from http://blog.matt-darby.com/2008/05/16/iterating-over-all-models-in-rails/
    # Thanks, Some Internet Guy
    def self.all_models
    klasses = []
    Object.constants.each do |o|
    klass = eval(o, TOPLEVEL_BINDING)
    if klass.is_a?(Class) && klass.superclass == ActiveRecord::Base
    klasses > ActiveRecordHelpers.all_models
    => [CachedModel, Treeitem]

    if called after accessing another object:

    >> t = Treeitem.find :first
    => #
    >> t.space
    => #
    >> ActiveRecordHelpers.all_models
    => [CachedModel, Space, Treeitem]

    Hmm….

Comments