Ruby / Rails时间助手方法

时间:2012-05-07 21:29:53

标签: ruby-on-rails ruby

我正在寻找帮助我格式化时间助手的助手类/方法/宝石。我正在查看传递Time.now实例的输出类似于以下内容:

"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

1 个答案:

答案 0 :(得分:8)

这样的帮助程序已经存在并且内置于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,如上所述!