I want to calculate how long the user has been a member of my app. I should display it as:
User member for 2y, 9m
To do so I've created method inside of User model
def member_for
#calculate number of months
month = (Time.current.year * 12 + Time.current.month) - (created_at.year * 12 + created_at.month)
#an array [years, months]
result = month.divmod(12)
if result[0].zero? && result[1].nonzero?
"User member for #{result[1]}m"
elsif result[1].zero? && result[0].nonzero?
"User member for #{result[0]}y"
elsif result[0].zero? && result[1].zero?
'User member for 1m'
else
"User member for #{result[0]}y, #{result[1]}m"
end
end
But honestly this code smells, isn't there some built-in method in Rails6 to do this better and make the code look a little cleaner?