简化多个if-then rake任务

时间:2012-09-29 19:30:41

标签: ruby-on-rails if-statement scheduled-tasks rake-task

我得到了下面的佣金任务,每天运行一次以解决我的申请中的一些赌注。但我很确定它可以简化,所以IF-THEN语句可以用s CASE stement代替。

我假设使用CASE选项运行多个IF语句需要更长时间才能运行相同的进程。这是对的吗?

我只是不确定如何将它从IF-THEN转换为CASE选项..

task :settle => :environment do
  @bets = Bet.where(:settle => false)

  @bets.each do |bet|

    if not bet.value.nil?

     if bet.price.value > bet.value and bet.buy == true then 
      bet.profitloss  = 10
      bet.settle      = true
      bet.save
     end

     if bet.price.value < bet.value and bet.buy == false then
      bet.profitloss  = 10
      bet.settle      = true
      bet.save
     end

     if bet.price.value > bet.value and bet.buy == false then
      bet.profitloss  = -10
      bet.settle      = true
      bet.save
     end

     if bet.price.value < bet.value and bet.buy == true then
      bet.profitloss  = -10
      bet.settle      = true
      bet.save
     end

     if bet.price.value = bet.value then
      bet.profitloss  = -10
      bet.settled     = true
      bet.save
     end 

   end
  end
end

2 个答案:

答案 0 :(得分:3)

似乎是

bet.settle总是如此 bet.profitloss是-10 除非(bet.price.value&gt; bet.value和bet.buy)或(bet.price.value&lt; bet.Value and!bet.buy) 在这种情况下它是10

从以下真值表中得到了这个

< bet | = bet | > bet | buy || settle || profit
  0   |   0   |   1   |  0  ||    1   ||   0
  0   |   0   |   1   |  1  ||    1   ||   1
  0   |   1   |   0   |  0  ||    1   ||   0
  0   |   1   |   0   |  1  ||    1   ||   0
  1   |   0   |   1   |  0  ||    1   ||   1
  1   |   0   |   1   |  1  ||    1   ||   0

所以你可以使用一个if语句完成整个事情,然后用测试编织。 :)

答案 1 :(得分:2)

也许你可以实现它:

task :settle => :environment do
@bets = Bet.where(:settle => false)

@bets.each do |bet|
  if not bet.value.nil?
    case 
    when bet.price.value > bet.value and bet.buy == true
      profitloss  = 10
    when bet.price.value < bet.value and bet.buy == false 
      profitloss  = 10
    when bet.price.value > bet.value and bet.buy == false
      profitloss  = -10
    when bet.price.value < bet.value and bet.buy == true 
      profitloss  = -10
    when bet.price.value = bet.value
      profitloss  = -10
    end
    if profitloss  
      bet.settled = true
      bet.profitloss = profitloss 
      bet.save
    end 
  end
end

拉出已结算并保存的东西可以让您在需要时轻松集成其他功能,而无需在每个if或when情况下进行复制。