MODEL_DIR = File.join(RAILS_ROOT, "app/models") # Rake task for updating all the popularities of is_popular models # Usage: rake popularity:update module Popularity # Return a list of the model files. If we have # command line arguments, they're assumed to be either # the underscore or CamelCase versions of model names. # Otherwise we take all the model files in the # app/models directory. def self.get_model_names models = ARGV.dup models.shift if models.empty? Dir.chdir(MODEL_DIR) do models = Dir["**/*.rb"] end end models end # We're passed a name of things that might be # ActiveRecord models. If the model matches _popularity # and we can find the class and it's a subclass of ActiveRecord::Base # and it responds to update_popularities, # then run that class's update_popularities method def self.update self.get_model_names.each do |m| class_name = m.sub(/\.rb$/,'') popularity_class = class_name.include?("_popularity") ? class_name.gsub("_popularity", "").camelize : nil if popularity_class klass = popularity_class.split('::').inject(Object){ |klass,part| klass.const_get(part) } rescue nil if klass && klass < ActiveRecord::Base && ! klass.abstract_class? && klass.respond_to?("update_popularities") puts "Updating Popularity For #{klass.name}" klass.update_popularities end end end end end