繁体   English   中英

我怎样才能使这个条件复杂的实例方法更符合Ruby的习惯?

[英]How can I make this conditional riddled instance method more Ruby idiomatic?

  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

该代码运行良好,外观看上去很笨拙。 有什么办法可以解决这个问题吗?

您可以如下简化。 请注意,您的代码是多余的。 如果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

我假设您无意间遇到了不平等现象(您需要<=不是>= )。 另外,如果您认为时差始终不超过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

关于什么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM