Tony
Tony

Reputation: 10208

Verbalize person age in Ruby on Rails

I need to verbalize the age of a person. Is there a Rails helper for that:

For example:

any ideas?

Upvotes: 1

Views: 241

Answers (1)

Sean Hill
Sean Hill

Reputation: 15056

You could customize the helper in the ActionView::Helpers::DateHelper module.

https://github.com/rails/rails/blob/4b1985578a2b27b170358e82e72e00d23fdaf087/actionpack/lib/action_view/helpers/date_helper.rb#L67

Other than than that, you can create your own helper pretty easily, without taking into account leap days... which may or may not be important.

def humanize_age(person)
  age = Date.today - person.birth_date
  years = (age / 1.year).to_i
  age = age % 1.year
  months = (age / 1.month).to_i
  age = age % 1.month
  days = (age / 1.day).to_i

  if years < 1
    if months < 1
      "#{days} days old"
    else
      "#{months} months old"
    end
  else
    "#{years} years, #{months} months old"
  end
end

This could be cleaned up a bit, and I haven't tested it, but this should work.

Upvotes: 2

Related Questions