我怎样才能使这个有条理的实例方法更加Ruby惯用?

时间:2013-08-17 01:28:39

标签: ruby-on-rails ruby idiomatic instance-method

  def short_remaining_time
    difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')

    # To display the short remaining time in an auction listing.
    if difference[:day] == 0 and difference[:hour] >= 1
      "#{difference[:minute]} minutos"
    elsif difference[:day] == 0 and difference[:hour] >= 23
      "#{difference[:hour]} horas"
    else
      if difference[:day] != 1
        "#{difference[:day]} dias"
      else
        "#{difference[:day]} dia"
      end
    end
  end

此方法位于我的Rails应用程序中的auction.rb模型中。

在我的一个观点中,我列出了系统中的所有拍卖,并且还显示了拍卖结束前剩余的时间。

根据时间的推移,我会显示days hoursminutes

代码工作正常,外观和感觉非常笨重。有没有办法对此进行修改?

3 个答案:

答案 0 :(得分:1)

您可以按照以下简化它。请注意,您的代码是多余的。如果difference[:hour] >= 23,则需要difference[:hour] >= 1,并且将由后者捕获,因此前一个条件永远不会被评估为真。这部分可以删除。

def short_remaining_time
  difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')
  case day = difference[:day]
  when 0
    if difference[:hour] >= 1 then "#{difference[:minute]} minutos"
    else "#{day} dias"
    end
  when 1 then "#{day} dia"
  else "#{day} dias"
  end
end

答案 1 :(得分:1)

我认为你的不平等无意中不正确(你需要<=而不是>=)。此外,如果您假设差异中的小时数总是不超过23,则您不需要检查(即,我们假设时间差是“标准化”)。所以我会这样修改它以保持你原来的意图:

  def short_remaining_time
    difference  = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')

    # To display the short remaining time in an auction listing.
    if difference[:day] == 0
      if difference[:hour] <= 1
        "#{difference[:minute]} minutos"
      else
        "#{difference[:hour]} horas"
      end
    else
      "#{difference[:day]} dia" + ((difference[:day] == 1) ? "" : "s")
    end
  end

答案 2 :(得分:1)

怎么样?
def short_remaining_time
  difference      = Time.diff(Time.now, created_at + 7.days, '%d - %H - %N')
  diff_in_minutes = difference[:day] * 3600 + difference[:hour] * 60

  case diff_in_minutes
    when 0..60      then  "#{difference[:minute]} minutos"
    when 61..3600   then  "#{difference[:hour]  } horas"
    when 3600..7200 then  "#{difference[:day]   } dia"
    else                  "#{difference[:day]   } dias"
  end
end