Feature proposal: Add units option to distance_of_time_in_words helper

In our app we need to display the amount of time passed since an object was created in the UI. Out of the box it looks like time_ago_in_words was going to do the job. However, in our case we need to know the time in a specific unit, in this case days. By happenstance the important numbers are in the 120 days range which causes time_ago_in_words to swap to ‘months’. We had to create custom method to handle this which partly duplicates the Rails code.

I have a patch to distance_of_time_in_words that allows the user to specify a units: option to force the returned value to be in the unit defined. For example,

?> distance_of_time_in_words(5.hours, 0, units: :minutes)
=> "300 minutes"
?> distance_of_time_in_words(5.hours, 0, units: :days)
=> "0 days"
?> distance_of_time_in_words(128.days, 0, units: :days)
=> "128 days"
?> distance_of_time_in_words(380.days, 0, units: :months)
=> "13 months"
?> distance_of_time_in_words(128.days, 0, units: :years)
=> "about 0 years"

This would uses the locale code that is already present in the method. Right now I didn’t consider a fallback if a time gets large, (e.g. user chooses minutes but the diff is 5 years so it results in a very large minute value) as it the user’s choice to keep that.

Looking for feedback and/or opinions on pushing such a patch up.

Huh. I forgot that this helper existed until reading your post.

I agree that its current features are inflexible and not suitable for a wide range of potential use cases. It also seems to violate the “opinion-free” nature of most Rails features, specifically the hard-coded ranges that control when it returns actual values vs. approximations.

But I don’t think extending distance_of_time_in_words is the answer. A look at the source reveals that it’s mostly hard-coded values and arbitrary decision points. So despite the method name, it’s not a generic converter of time differences into words.

Why not use simple math to get the number of days? Or create a helper method that does so? (SomeObj.created_at - Time.now) / SECONDS_PER_DAY

@djmolny are you saying just create new, separate helpers rather than hacking into the existing method?

For example, time_ago_in_days or time_ago_in_minutes

Yes. That should only require a few lines of code.