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}

Sorry, comments are closed for this article.