Expose age_range instead of date_of_birth for Voter/User class

This commit is contained in:
Alberto Miedes Garcés
2017-01-02 14:12:37 +01:00
parent f4e0ef7eea
commit 0b4004042f
5 changed files with 43 additions and 4 deletions

View File

@@ -244,6 +244,10 @@ class User < ActiveRecord::Base
end end
delegate :can?, :cannot?, to: :ability delegate :can?, :cannot?, to: :ability
def age_range
AgeRangeCalculator::range_from_birthday(self.date_of_birth).to_s
end
private private
def clean_document_number def clean_document_number

View File

@@ -5,7 +5,7 @@ API_TYPE_DEFINITIONS = {
}, },
Voter => { Voter => {
gender: :string, gender: :string,
date_of_birth: :string, age_range: :string,
geozone_id: :integer, geozone_id: :integer,
geozone: Geozone geozone: Geozone
}, },

View File

@@ -0,0 +1,15 @@
class AgeRangeCalculator
MIN_AGE = 16
MAX_AGE = 1.0/0.0 # Infinity
RANGES = [ (MIN_AGE..25), (26..40), (41..60), (61..MAX_AGE) ]
def self.range_from_birthday(dob)
# Inspired by: http://stackoverflow.com/questions/819263/get-persons-age-in-ruby/2357790#2357790
now = Time.current.to_date
age = now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
index = RANGES.find_index { |range| range.include?(age) }
index ? RANGES[index] : nil
end
end

View File

@@ -0,0 +1,14 @@
require 'rails_helper'
describe AgeRangeCalculator do
subject { AgeRangeCalculator }
describe '::range_from_birthday' do
it 'returns the age range' do
expect(subject::range_from_birthday(Time.current - 1.year)).to eq(nil)
expect(subject::range_from_birthday(Time.current - 26.year)).to eq(26..40)
expect(subject::range_from_birthday(Time.current - 60.year)).to eq(41..60)
expect(subject::range_from_birthday(Time.current - 200.year)).to eq(61..subject::MAX_AGE)
end
end
end

View File

@@ -469,4 +469,10 @@ describe User do
end end
describe "#age_range" do
it 'returns string representation of age range' do
user = create(:user, date_of_birth: Time.current - 41.years)
expect(user.age_range).to eq('41..60')
end
end
end end