That's not a philosophical post, but sometimes we have to deal with the past and/or future. That's totally fine. Maybe you have to figure out if something happened in the past or if it’s going to happen in the future. Using the same approach of my previous post [POST], I would like to share the Rails extensions to Ruby built-in Date class I usually use when I am working.
Today (the date this post was written) is Sat, 03 Mar 2012. And Rails give us a nice way to have this information, using the “today” method.
In the same way, we can also discover which day would be tomorrow or which day was yesterday, using “tomorrow” and “yesterday”:
Which day was in the beginning of the X (where X could be: week, month, year)? You might also want to know which day will be in the end of X (the same X). We have a set of methods ready to help us out.
Using the same date
You can ask a date instance information about the beginning/ending of: week, month and year:
With the same name pattern, but with a slightly different result, Rails defines the methods “beginning_of_day” and “end_of_day”. It will return an ActiveSupport::TimeWithZone instance, instead of a Date, containing time details.
What would be the first thing you would do if you had a time travel machine? I bet you are thinking about lots of things just right now, but before you continue, let me explain why I did this question. Rails defines a method that allow you travel to a specific date, just like a time travel machine. Rails defines it as “advance” and we are going to play with it.
Our initial date will be today:
Let’s travel to the future, 1 year from now:
Maybe one year is too much, let’s use 1 month instead:
Well, you can define your own trip using different combinations of: years, months, weeks and days. It allows us to do things like:
Perhaps you are looking for a simple way to change an existent date instance. For times like this, you have “change”:
You can change pretty much everything and have a complete new date.
This is a limited list of extensions to Ruby Date extensions provided by Rails. This list is based on my experience and needs using it. For a more detailed list, visit the Rails documentation site or browse its source code.
I am open sourcing a project that I have been using a lot lately. You can easily define routes and some rules...
Benchmarking Ruby and Erlang
Open sourcing a lib I created to benchmark Rails apps, using ActiveSupport::Notifications
You invested thousands of hours learning Rails and how to master its features to build web applications. This book will help you to learn Phoenix, using the knowledge you already have.Get the book