diff --git a/app/models/user.rb b/app/models/user.rb index 03f2db27b..04ca708a9 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -244,6 +244,10 @@ class User < ActiveRecord::Base end delegate :can?, :cannot?, to: :ability + def age_range + AgeRangeCalculator::range_from_birthday(self.date_of_birth).to_s + end + private def clean_document_number diff --git a/config/initializers/graphql.rb b/config/initializers/graphql.rb index fdb5975e3..6fb30ca45 100644 --- a/config/initializers/graphql.rb +++ b/config/initializers/graphql.rb @@ -4,10 +4,10 @@ API_TYPE_DEFINITIONS = { username: :string }, Voter => { - gender: :string, - date_of_birth: :string, - geozone_id: :integer, - geozone: Geozone + gender: :string, + age_range: :string, + geozone_id: :integer, + geozone: Geozone }, Debate => { id: :integer, diff --git a/lib/age_range_calculator.rb b/lib/age_range_calculator.rb new file mode 100644 index 000000000..acb12e19e --- /dev/null +++ b/lib/age_range_calculator.rb @@ -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 diff --git a/spec/lib/age_range_calculator_spec.rb b/spec/lib/age_range_calculator_spec.rb new file mode 100644 index 000000000..a6fd183ed --- /dev/null +++ b/spec/lib/age_range_calculator_spec.rb @@ -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 diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index ed0bac164..ca59cb288 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -469,4 +469,10 @@ describe User do 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