From cc6d841978448f0ae3648a0d2127e0398d396633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juanjo=20Baza=CC=81n?= Date: Wed, 25 Jan 2017 17:16:17 +0100 Subject: [PATCH] refactors age calculation --- app/models/poll/voter.rb | 7 ++++--- app/models/user.rb | 5 ++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/app/models/poll/voter.rb b/app/models/poll/voter.rb index a2d46053a..4c9314f12 100644 --- a/app/models/poll/voter.rb +++ b/app/models/poll/voter.rb @@ -42,11 +42,12 @@ class Poll private - def voter_age(date_of_birth) - if date_of_birth.blank? + def voter_age(dob) + if dob.blank? nil else - ((Date.today - date_of_birth.to_date).to_i / 365.25).to_i + now = Time.now.utc.to_date + now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1) end end diff --git a/app/models/user.rb b/app/models/user.rb index 80b0cb621..7c72ab4b3 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -250,7 +250,10 @@ class User < ActiveRecord::Base if date_of_birth.blank? nil else - ((Date.today - date_of_birth.to_date).to_i / 365.25).to_i + now = Time.now.utc.to_date + now.year - date_of_birth.year - ( + (now.month > date_of_birth.month || (now.month == date_of_birth.month && now.day >= date_of_birth.day) + ) ? 0 : 1) end end