Ruby_on_rails_improvement_Railsware

Rails 4.0 ActiveSupport small improvement

| 2 Comments

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.

Preface

Working on Interstellar, I’ve found out that
ActiveSupport has a lot of useful methods like Date#beginning_of_week, 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…

Ruby On Rails development
The first patch I come up with was an extension that makes possible to pass week start to beginning_of_week and 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: next_week and prev_week.
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 beginning_of_week inside next_week and 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.

Examples:

Instead of epilogue

There’s a lot of stuff out there that still should be improved.
For example, 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:

It’s time to contribute, so go for it!

Share
* Railsware is a premium software development consulting company, focused on delivering great web and mobile applications. Learn more about us.
  • http://k776.tumblr.com/ Kieran P

    This would be useful for beginning_of_year too for e.g. financial applications that revolve around the tax year. Apr 1st-Mar31st. beginning_of_year(:april) => Apr 1st

    • http://twitter.com/gregolsent Innokenty Mikhailov

      Sounds like a good idea

Want to get more of Railsware blog?

RSS FEED

We're always ready to help!

CONTACT US