Created
November 4, 2014 14:49
-
-
Save pjanuario/e0b796b352f905ac7edc to your computer and use it in GitHub Desktop.
This gist contains some info about calculating users age avoiding leap year issues.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User | |
attr_reader :born_on | |
def age(today = Time.now.utc) | |
return nil unless self.born_on.present? | |
((today.to_time - self.born_on.to_time) / 1.year).to_i | |
end | |
end | |
describe User do | |
describe '#age' do | |
context 'when born_on is not set' do | |
before { subject.born_on = nil } | |
its(:age) { should_not be } | |
end | |
it "calculates the user's age when born_on is set" do | |
on_given_day = Date.civil(2013, 4, 30) | |
subject.born_on = Date.civil(1968, 5, 1) | |
subject.age(on_given_day).should eq(44) | |
end | |
context 'on leap year' do | |
before { subject.born_on = Date.civil(1996, 2, 29) } | |
it "calculates the user's age" do | |
on_given_day = Date.civil(2014, 11, 4) | |
subject.age(on_given_day).should eq(18) | |
end | |
it "calculates the user's age before birth day" do | |
on_given_day = Date.civil(2012, 2, 28) | |
subject.age(on_given_day).should eq(15) | |
end | |
it "calculates the user's age after birth day" do | |
on_given_day = Date.civil(2012, 3, 1) | |
subject.age(on_given_day).should eq(16) | |
end | |
it "calculates the user's age on birth day" do | |
on_given_day = Date.civil(2012, 2, 29) | |
subject.age(on_given_day).should eq(16) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment