My First Ruby/Rails Contribution: SmartMonth

Our big project at Panoctagon had a lot to do with time and dates, so we’ve been developing a series of Rails plugins that make our jobs easier. I had a lot of fun building this one, and I could see other people finding this interesting, so we decided to open source this one. I think it’d make a great addition to Rails core (if I do say so myself :P), but I am not really up to all the effort involved. Instead I created a simple to use, documented, and tested plugin that works with Rails!

So what does it do? Basically, it makes date month values more meaningful by adding a new Month class that can do complex(ish) calculations against the days of the month for you. It also allows you to treat a Month as an enumerable container, allowing you to iterate through the days of the month like an array.

Lets peek at some example snippets:

Getting The First Tuesday of September 2009

Month.september(2009).first_tuesday #=> Date object
Month.new(9,2009).first(:tuesday) #=> Date object

Getting Every Friday in August 2008

Month.august.every_friday #=> Array of Date objects
Month.new("August").every(:friday) #=> Array of Date objects

Getting Every Thursday and Saturday in June 2007

Month.june(2007).every_thursday_and_saturday #=> Hash of Arrays of Date objects
Month.new("June",2007).every(:thursday,:friday) #=> Hash of Arrays of Date objects

Getting The Last Monday in April 2005

Month.april(2005).last_monday #=> Date object
Month.new("April",2005).last(:monday) #=> Date object

Enumerating Through the Month of August 2008

month = Time.now.month #=> Month object of the current time requested month.each do |day| day.to_s #=> Week day name ie: Saturday, Sunday, etc. day.to_i #=> Date value in context of the month ie: 1..31 end

Other Odds and Ends

Month.april.size #=> total number of days in that month Month.august.next #=> returns a month object populated with August Time.now.month #=> returns the current month in context to the #now response Month[5] #=> May Month object access as array index Month[:april] #=> April month object access as hash key

So, as you can see, it saves a lot of time and calculations and keeps it easy for you to treat months as essentially a container! Really useful for doing complex calculations against dates.

If you would like to use my plugin, feel free, I’ve released it under MIT, and its located at my github account. Please give me some props if you do, or send me a line.