Rails shorter “time_ago_in_words”

前端 未结 2 865
鱼传尺愫
鱼传尺愫 2021-02-06 00:06

Is there a different time calculation in rails besides \"time_ago_in_words\"?? I want to be able to use just \'h\' for hours \'d\' days \'m\' for months... ex. 3d, or 4h, or 5m<

相关标签:
2条回答
  • 2021-02-06 00:33

    Here's some other ways to do it. You run the method like normal, and then you use gsub on the string.

    Chained

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

    Hash

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

    Block

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

    They all do the same except for when the string is "less than a minute". The chained solution returns "less than a minute". The hash solution returns "less". The block solution returns "lesst".

    Just change the locale file for this one case

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

    Or add a return to clause at the top of your method

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

    Note: Does not include solutions for include_seconds: true option.

    0 讨论(0)
  • 2021-02-06 00:37

    The components that make up this string can be localised, and are in the datetime.distance_in_words namespace

    For example stick

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

    And rails will say 10m instead of 10 minutes. Repeat as needed for hours, seconds days etc. you can check locales/en.yml in action_view for all the keys.

    If you only want the short format you could create a pseudo locale that only used those keys and use it like so

    time_ago_in_words created_at, false, :locale => :en_abbrev
    
    0 讨论(0)
提交回复
热议问题