While working on one of our client projects, I was asked to create a search for users' birthdays. Instantly, I remembered what problems I had with it in the past, like taking care of not only finding the right dates by only day and month, but also, checking for birthdays today, any upcoming birthdays, or even just looking up user's age based on that information.
So, to never ever repeat that code again (and to keep the code DRY), I've decided to write a simple gem specifically for this stuff. And thus the birthday gem was born.
The gem has been tested against Rails 3 (3.0.9) and Rails 2 (2.3.14), and depends on ActiveRecord and ActiveSupport (for inflections), making it a perfect fit for Rails. It is possible to use it outside Rails project, but you are required to use ActiveRecord as your ORM framework.
The gem works with MySQL and PostgreSQL adapters, but you can write your own adapters, if you need to. If you do so, it would be good to fork the gem and add it there for everybody to use. :)
So, how does it actually work?
Handling birthdays wasn't that easy before. Here's what you have to do in your model:
That's all. This one line enables extra actions on the "birthday" field (of DATE or DATETIME types) in your database. For example from now on you can search for birthdays
- on a specific date:
- between a specific range:
- and even at the turn of the years:
All these methods are essentially scopes, so you could also do something like:
On top of that, you get convenience methods for single records, like getting the age:
You can get any field to behave like this. For example, let's say we want marriage anniversaries:
And it's done, from now on you have convenient scopes to search and handle anniversaries:
I've done this gem, because I never ever want to write this piece of code again, I'd rather spend my time on actually coding the important stuff in applications, than to fiddle around with dates and birthdays. Hope this gem will be of some use to you. If not, fork it, and patch it to your needs! :)