Created
April 17, 2012 07:01
-
-
Save robinclart/2404095 to your computer and use it in GitHub Desktop.
A module and a class to deal with birthday
This file contains 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
require "date" | |
module Birthday | |
def birthday(year_of_birthday = Date.today.year) | |
if birthdate.leap? | |
year_of_birthday += 1 until Date.new(year_of_birthday).leap? | |
end | |
Date.new(year_of_birthday, birthdate.month, birthdate.day) | |
end | |
def birthday?(other_date = Date.today) | |
other_date.month == birthdate.month && other_date.day == birthdate.day | |
end | |
def years_from(other_date) | |
((other_date - birthdate).to_i / 365.2422).floor | |
end | |
def years_old | |
years_from Date.today | |
end | |
def next_birthday(other_date = Date.today) | |
birthday other_date.year + (before_birthday?(other_date) ? 0 : 1) | |
end | |
def previous_birthday(other_date = Date.today) | |
birthday other_date.year + (after_birthday?(other_date) ? 0 : -1) | |
end | |
def before_birthday?(other_date = Date.today) | |
other_date < birthday(other_date.year) | |
end | |
def after_birthday?(other_date = Date.today) | |
other_date > birthday(other_date.year) | |
end | |
def centenarian?(other_date = Date.today) | |
years_from(other_date) >= 100 | |
end | |
def newborn?(other_date = Date.today) | |
years_from(other_date) == 0 | |
end | |
end | |
# Examples | |
# | |
# puts Birthdate.parse("02 nov 1986").next_birthday | |
# # >> 2012-11-02 | |
class Birthdate < Date | |
include Birthday | |
def birthdate | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment