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,
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
I think this would be a useful addition. Being able to specify the unit gives developers more control without having to duplicate the existing Rails code.