【问题标题】:Rails shorter "time_ago_in_words"Rails 更短的“time_ago_in_words”
【发布时间】:2012-09-17 12:48:01
【问题描述】:

除了“time_ago_in_words”之外,rails中是否有不同的时间计算?我希望能够只使用 'h' 几个小时 'd' 天 'm' 几个月......例如。 3d、4h、5m

我的代码现在...

<%= time_ago_in_words(feed_item.created_at) %> ago.

【问题讨论】:

    标签: ruby-on-rails time


    【解决方案1】:

    在较新版本的 rails 中,您可以将范围指定为方法的选项,如下所示:

    time_ago_in_words(company.updated_at, scope: 'datetime.distance_in_words.abbrv')
    

    那么你只需要像这样构造你的常规 i18n 文件:

    en:
      datetime:
        distance_in_words:
          abbrv:
            about_x_hours:
              one: ~ 1h
              other: ~ %{count}h
            about_x_months:
              one: ~ 1mo
              other: ~ %{count}mo
            about_x_years:
              one: ~ 1y
              other: ~ %{count}y
            almost_x_years:
    ...
    

    文档中也提供了此信息: https://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

    【讨论】:

      【解决方案2】:

      构成该字符串的组件可以本地化,并且位于 datetime.distance_in_words 命名空间中

      例如棍子

      en:
        datetime:
          distance_in_words:
            x_minutes:
              one: "1m"
              other: "%{count}m"
      

      Rails 会说 10m 而不是 10 分钟。根据需要重复几小时、几秒、几天等。您可以在 action_view 中检查 locales/en.yml 以获取所有键。

      如果你只想要短格式,你可以创建一个只使用这些键的伪语言环境并像这样使用它

      time_ago_in_words created_at, false, :locale => :en_abbrev
      

      【讨论】:

      【解决方案3】:

      这里有一些其他的方法来做到这一点。你像往常一样运行该方法,然后在字符串上使用gsub

      连锁

      string.gsub(/ mi.*/, 'm')
            .gsub(/ h.*/, 'h')
            .gsub(/ d.*/, 'd')
            .gsub(/ mo.*/, 'mo')
            .gsub(/ y.*/, 'y')
      

      哈希

      string.gsub(/ .+/, { 
        ' minute'=> 'm', ' minutes'=>'m', 
        ' hour' => 'h', ' hours' => 'h', 
        ' day' => 'd', ' days' => 'd', 
        ' month' => 'mo', ' months' => 'mo', 
        ' year' => 'y', ' years' => 'y' 
      })
      

      阻止

      string.gsub(/ .+/) { |x| x[/mo/] ? 'mo' : x[1] }
      

      除了字符串为"less than a minute" 之外,它们都执行相同的操作。链式解决方案返回"less than a minute"。哈希解决方案返回"less"。块解返回"lesst"

      只需更改此案例的语言环境文件

      en:
        datetime:
          distance_in_words:
            less_than_x_minutes:
              one: '<1m'
      

      或者在方法的顶部添加一个 return to 子句

      def my_method(string)
        return '<1m' if string == 'less than a minute'
        # code
      end
      

      注意:不包括include_seconds: true 选项的解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 1970-01-01
        • 2015-09-24
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多