诗歌rails之自定义Rake任务
我们经常用rake db:migrate来做数据库迁移
我们还可以使用rake -T来列出可得到的rake任务
让我们在store这个Rails程序中创建一个自己的Rake任务
我们创建store/lib/tasks/ryanb.rake:
我们现在可以使用rake greet或rake ask来运行
对于相关联的rake任务我们可以这样做:
名字空间
提取公用方法:
我们还可以使用rake -T来列出可得到的rake任务
让我们在store这个Rails程序中创建一个自己的Rake任务
我们创建store/lib/tasks/ryanb.rake:
- task :greet do
- puts "Hello World!"
- end
- task :ask do
- puts "How are you?"
- end
对于相关联的rake任务我们可以这样做:
- task :greet do
- puts "Hello World!"
- end
- task :ask => :greet do
- puts "How are you?"
- end
ask任务依赖于greet任务,当我们运行rake ask时会先调用greet任务
需要Rails环境的任务
- task :pick_winner => :environment do
- user = User.find(:first, : order => 'RAND()')
- puts "Winner #{user.name}"
- end
- namespace :pick do
- task:winner => :environment do
- user = User.find(:first, : order => 'RAND()')
- puts "Winner #{user.name}"
- end
- end
- 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(User).name}"
- end
- def "Pick a random prize as the prize"
- task :all => [:prize, :winner]
- def pick(model_class)
- model_class.find(:first, : order => 'RAND()')
- end
- end
转载: http://www.cnblogs.com/orez88/articles/1520504.html