0
  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

这个方法auction.rb在我的 Rails 应用程序的模型中。

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

根据时间长短,我要么显示days hours要么minutes

代码运行良好,只是看起来和感觉非常笨拙。有没有办法让这件事变得更美一点?

4

3 回答 3

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
于 2013-08-17T01:38:36.670 回答
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
于 2013-08-17T01:48:26.193 回答
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
于 2014-01-28T13:15:54.917 回答