2012-05-07 26 views
1

我正在尋找一個輔助類/方法/ gem,它會幫助我格式化時間幫手。我期待傳遞Time.now的實例後的輸出是類似以下內容:Ruby/Rails時間幫手方法

"1 minute ago" 
"2 minutes ago" 
"1 hour ago" 
"2 hours ago" 
"1 day ago" 
"2 days ago" 
"over a year ago" 

我開始寫這樣的事情,但它的將是漫長而痛苦的,我覺得像這樣的事情有存在。唯一的缺點是我需要用我自己的措辭,因此需要有一個格式化的東西..

def time_ago_to_str(timestamp) 
    minutes = (((Time.now.to_i - timestamp).abs)/60).round 
    return nil if minutes < 0 
    Rails.logger.debug("minutes #{minutes}") 

    return "#{minutes} minute ago" if minutes == 1 
    return "#{minutes} minutes ago" if minutes < 60 
    # crap load more return statements to follow? 
    end 

回答

7

這樣的幫手已經存在,並且是內置在Rails的:

http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words

time_ago_in_words(5.days.ago) 
=> "5 days" 

編輯:

如果您想自定義的措辭,你可以創建自定義I18n語言環境,例如,我在config/locales/time_ago.yml創建了一個名爲TIME_AGO:

time_ago: 
    datetime: 
    distance_in_words: 
     half_a_minute: "half a minute" 
     less_than_x_seconds: 
     one: "less than 1 second" 
     other: "less than %{count} seconds" 
     x_seconds: 
     one: "1 second" 
     other: "%{count} seconds" 
     less_than_x_minutes: 
     one: "less than a minute" 
     other: "less than %{count} minutes" 
     x_minutes: 
     one: "1 min" 
     other: "%{count} mins" 
     about_x_hours: 
     one: "about 1 hour" 
     other: "about %{count} hours" 
     x_days: 
     one: "1 day" 
     other: "%{count} days" 
     about_x_months: 
     one: "about 1 month" 
     other: "about %{count} months" 
     x_months: 
     one: "1 month" 
     other: "%{count} months" 
     about_x_years: 
     one: "about 1 year" 
     other: "about %{count} years" 
     over_x_years: 
     one: "over 1 year" 
     other: "over %{count} years" 
     almost_x_years: 
     one: "almost 1 year" 
     other: "almost %{count} years" 

現在,你可以使用的語言環境與distance_of_time_in_words

# distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {}) 
distance_of_time_in_words(5.minutes.ago, Time.now, true, {:locale => "time_ago"}) 
=> "5 mins" 

你當然可以將它添加到config/locales/en.yml,並完全覆蓋它們應用範圍廣泛,您可以按照上面提到的方式撥打time_ago_in_words

+0

time_ago_in_words的問題是它不允許我使用自己的格式。如果我想在5分鐘前使用,而不是在5分鐘前使用? – randombits

+0

我敢肯定,distance_of_time_in_words會這麼做,因爲它接受I18n語言環境作爲選項。我會嘗試做一個例子;但是您始終可以複製源代碼並進行修改:http://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words – kwarrick