#66 Custom Rake Tasks

Rake is one of those tools that you don't realize how powerful it is until you start using it. In this episode you will learn how to create custom rake tasks and improve them by using rake features.
namespace :pick do
  desc "Pick a random user as the winner"
  task :winner => :environment do
    puts "Winner: #{pick(User).name}"
  end

  desc "Pick a random product as the prize"
  task :prize => :environment do
    puts "Prize: #{pick(Product).name}"
  end
  
  desc "Pick a random prize and winner"
  task :all => [:prize, :winner]
  
  def pick(model_class)
    model_class.find(:first, :order => 'RAND()')
  end
end

你可能感兴趣的:(task)