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<
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.
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