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!

Mike Mayoabout 2 years ago

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!

bryanabout 2 years ago

Hey Matt,

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

  1. bw: hijacked from http://blog.matt-darby.com/2008/05/16/iterating-over-all-models-in-rails/
  2. 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….

keithover 1 year ago

I believe you have a typo. You need to escape that slash in your regexp.

i.e.
Dir.glob( File.join( RAILS_ROOT, ‘app’, ‘models’, ‘*.rb’) ).map{|path| path[/.\/(.).rb/,1] }

Cheers!

Auditing for attr_accessible « A Fresh Cupover 1 year ago

[…] tip Matt for the snippet to find all models). Possibly related posts: (automatically generated)Search Driven […]

Say your thing

Name:
Email:
URL:
$0.02: