2013-08-17 29 views
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 

此方法位於我的Rails應用程序的auction.rb模型中。如何讓這個有條件的實例化方法更符合Ruby的慣用方法?

在我的一個觀點中,我列出了系統中的所有拍賣,並且還顯示了在拍賣結束之前還剩多少時間。

根據時間的長短,我會顯示dayshoursminutes

該代碼工作正常,只是看起來感覺非常笨重。有沒有辦法讓這一點變得容易一些?

回答

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

我假設你有你的不平等無意中不太對勁(你需要<=>=)。此外,如果您認爲差異的小時數總是不超過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 
+0

我得到這個錯誤:'未繳的隱式轉換成String'。如果'difference [:day]'不是1,它試圖將'nil'轉換成字符串。 – sergserg

+0

@Serg,我更新它來處理'nil'。 – lurker

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