Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Check for under age (See related posts)

This function can be used to check if a user is underage.

Note: This is using rails core extensions. It'd need to be modified a bit for a pure ruby implementation.

def underage?(birthday)
  18.years.ago < birthday
end

Comments on this post

dcmanges posts on Nov 28, 2006 at 13:21
I would allowing passing in the age as:
def underage?(birthday, age = 18)
  age.years.ago < birthday
end

so you could also use this to see if somebody is under 21 by calling
underage?(user.birthday, 21)
moneypenny posts on Nov 28, 2006 at 20:45
You might also extend Integer like so:
class Integer
  def underage?( birthday )
    self.years.ago < birthday
  end
end

And then do
21.underage?( birthday )


However, I'm using a Date for the birthday and I get
ArgumentError: comparison of Time with Date failed
        from (irb):3:in `<'
        from (irb):3:in `underage?'
        from (irb):6

It seems most logical to use a Date and not a Time for someone's birthday, so there should be some kind of conversion to handle this.
MarcLove posts on Nov 30, 2006 at 01:55
An important note: The Rails ActiveSupport Time Extensions are only approximations of time, so if you're looking for complete accuracy, don't use them. If we're looking for accuracy, then we want to work with date objects.

1.year #=> 31557600 (which is 365.25 days times the number of seconds in a day)


If you're just looking to validate on record creation that a user is old enough, use the following validation:
validates_each :birthdate do |record, attr, value|
  record.errors.add.attr, "You're not old enough." if value > Date.new((Date.today.year - 18),(Date.today.month),(Date.today.day))
end


If you want to calculate a user's age:
def age
  age = Date.today.year - read_attribute(:birthdate).year
  if Date.today.month < read_attribute(:birthdate).month || 
  (Date.today.month == read_attribute(:birthdate).month && read_attribute(:birthdate).day >= Date.today.day)
    age = age - 1
  end
  return age
end
jrm02t posts on Dec 01, 2006 at 15:36
Ah, *great* input.

Thanks guys!

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts