I recently needed to iterate over all the ActiveRecord models in the rake factory:generate task for factories-and-workers.

I originally tried to iterate over Object.constants (like John Philip Green’s find_invalid rake task) but that seemed a bit clunky to me, and didn’t really work for my purposes.

Here’s how I did it:

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

actionmailer ActionView ActiveRecord activesupport ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factories-and-workers factory pattern filemerge find and replace finder fink fixtures fun functional testing gem git google maps helper helpers imagemagick Intertrust javascript jquery jrails logo math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism prototype.js rails rails gotcha rails,patch,validations railsconf rake rmagick RSA encryption ruby script shoulda subversion SyncTV TDD testing textmate tips tricks unique hashes unix shell validation view yaml zebra stripes