Expose age_range instead of date_of_birth for Voter/User class
This commit is contained in:
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
},
|
},
|
||||||
|
|||||||
15
lib/age_range_calculator.rb
Normal file
15
lib/age_range_calculator.rb
Normal 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
|
||||||
14
spec/lib/age_range_calculator_spec.rb
Normal file
14
spec/lib/age_range_calculator_spec.rb
Normal 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
|
||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user