2012-05-07 15 views
1

私は時間ヘルパーをフォーマットするのに役立つヘルパークラス/メソッド/宝石を探しています。私は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

このようなヘルパーがすでに存在し、内蔵されてレールに..フォーマッタで何かが必要なので、私は、私自身の文言を使用することが必要である:

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

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

EDIT:あなたは言葉遣いをカスタマイズしたい場合は

カスタムを作成することができますI18nロケールは、例えば、私はconfig/locales/time_ago.ymlに1と呼ばれる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