by simon baird

Wednesday, October 06, 2010

beginning_of_fortnight method for Ruby on Rails

You might know that Rails provides a bunch of useful extensions to the Time class with methods like beginning_of_week, beginning_of_month, etc.

For my application (a thing with fortnightly billing periods) I wanted to define a beginning of fortnight method to consistently calculate the beginning (and end) of a fortnight. Here's how it ended up (both short and sweet):

(Note that there's no special reason to use epoch. Any other day would work just as well probably).

Does it work?

Put beginning_of_fortnight.rb in config/initializers.

Note that there is already a Numeric#fortnights method in ActiveSupport so we can use things like 2.fortnights without needing any extentions.

No comments: