A few days ago my patch with the
beginning_of_week config option has been merged to Rails master, so starting from Rails 4.0 we’ll gain full control over the week start day.
Working on Interstellar, I’ve found out that
ActiveSupport has a lot of useful methods like
Date#end_of_week and many others.
However, there was a small thing that was quite a bit annoying:
all those API methods were tied to Monday as the first day of a week.
Not a big deal while developing web applications targeted to European market, but working on a US oriented stuff it might be useful to set Sunday as the beginning of a week.
Sure, you can fix this in a couple of methods… But hey, we are open source community, right?
We can patch it up baby…
The first patch I come up with was an extension that makes possible to pass week start to
end_of_week methods. It was accepted and merged into Rails 3.2 relatively fast.
And all was great, but there was another bunch of cool API methods:
They already have a single argument: a day in next (previous) week. That said, we cannot pass week start as an argument to these guys.
One of the possible solutions was an application wide config option for the week start.
In this case, we can use
prev_week without having to pass the start of the week manually.
So I hit another pull request with the
beginning_of_week config option.
It took more than 6 months to get this merged, and now I’m happy as I can be.
Since Rails 4.0 we’ll get full access to ActiveSupport calendaring API.
Time.now.beginning_of_week.to_date #=> Mon, 22 Oct 2012
Time.now.beginning_of_week(:sunday).to_date #=> Sun, 21 Oct 2012
Date.beginning_of_week = :thursday
Time.now.next_week.to_date #=> Thu, 25 Oct 2012
Instead of epilogue
There’s a lot of stuff out there that still should be improved.
Date now knows too much about
Week. Begging for a separate class (as Jeremy stated).
Another thing is that Rails stores week days in a different way than Ruby:
Date::DAYS_INTO_WEEK[:monday] #=> 0
Time.now.monday.wday #=> 1 (because Ruby stores Sunday as zero week day)
It’s time to contribute, so go for it!