【发布时间】:2012-11-08 20:49:17
【问题描述】:
我有一个应用程序,用户可以在其中互相下注,当结果加载到应用程序中时,我使用 Rake 任务来结算赌注。我在 Heroku 上运行,所以我每半小时使用他们的调度服务来执行这个 Rake 任务。
这很好用,但我更希望在数据库中保存/更新结果时运行 Rake 作业。
如何转换 Rake 任务,以便可以从我的模型中运行它,如下所示。如果我可以从控制器运行它也可能会很好,因为我可能有几种需要结算过程的情况。
class Spotprice < ActiveRecord::Base
belongs_to :spotarea
belongs_to :product
after_save :settlement
end
我的 Rake 任务现在看起来像这样:
task :settlement => :environment do
puts "Settlement in progress..."
puts "-------------------------"
puts " "
puts " "
puts "BETS:"
puts "-------------------------"
# Bet settlement
@bets = Bet.where(:settled => false)
@bets.find_each do |bet|
if not bet.choice.spotprice.nil?
case
when bet.choice.spotprice.value > bet.choice.value && bet.buy == true
profitloss = 10
puts "#{bet.id}: Win (1)"
when bet.choice.spotprice.value < bet.choice.value && bet.buy == false
profitloss = 10
puts "#{bet.id}: Win (2)"
when bet.choice.spotprice.value > bet.choice.value && bet.buy == false
profitloss = -10
puts "#{bet.id}: Loose (3)"
when bet.choice.spotprice.value < bet.choice.value && bet.buy == true
profitloss = -10
puts "#{bet.id}: Loose (4)"
when bet.choice.spotprice.value == bet.choice.value
profitloss = -10
puts "#{bet.id}: Loose (5)"
end
if profitloss
bet.settled = true
bet.profitloss = profitloss
bet.save
end
end
if bet.choice.settled == true
bet.choice.settled = false
bet.choice.save
end
end
# Pusher update
Pusher["actives"].trigger("updated", {:message => "Settlement completed"}.to_json)
end
【问题讨论】:
-
你可以把它放在
lib的一个文件里,然后在需要的时候调用它。你可以做一些棘手的事情,比如设置观察者来观察模型何时被保存,并做出相应的反应。您还可以使用 PrivatePub 向您的视图发送异步方法来执行提醒用户等操作。 -
嗨.. 我只是觉得从模型、控制器等运行 Rake 任务并不是最佳实践。它们只能从某种 Cron 调用。我有什么错误的印象吗:)
-
哦,对不起,我没有很好地解释自己。那是我的错。我的意思是您可以将代码从 rake 任务中取出,并将其放在
lib的类中。您将不再有 rake 任务。该代码将只是一个常规的 ruby 方法(只是在lib中提供,因为它不是模型或任何东西),然后从任何地方调用它。 -
现在看这更有意义了 :) 你能告诉我
libdirectory 中的文件应该是什么样子吗?我在想文件的开头 - 是什么与Module或应该是'class Spotprice
标签: ruby-on-rails rake helper