
Range and Date in Ruby on Rails
In one of my previous posts, I showed an example of using the Range object in Ruby. Ruby on Rails has its own extension of the Date class, which makes working with dates very convenient. Zero parsing, zero conversion - we write our date handling helpers like natural language, making the code read like fluent English, sometimes letting us forget we're dealing with a programming language. Today I'll show you how to use a combination of Range and Date classes in Ruby on Rails to create readable date checking.
Ruby's nature allows for another super cool thing - extending core classes. In this example, we'll extend the Date class provided by Ruby on Rails.
Case:
In various reporting modules or dashboards, you often encounter operations involving date comparisons, filtering dates from the previous year, month, or week. Working with dates in RoR is already super pleasant, but the following snippet makes it even more enjoyable.
We're extending the Date
class here.
First, I'm declaring an instance method that will check if a date falls within a given range. This is an instance method, which means it will be called on an instance or, more simply put - directly on a date.
Next, I'm extending the Date
class with static methods.
I'm overriding the today
method.
Then I create a previous_year
method using Range, which returns a date range for the previous year.
Next, I create a current_year
method that returns a date range for the current year.
Following that, I create methods for previous_month
, current_month
, previous_week
, and current_week
.
After creating these helper methods, we can easily write conditions that check dates.
Połączenie klas Range
i Date
w Ruby on Rails to dobry pomysł na poprawę czytelności kodu.
W dokumentacji przeczytasz o klasie Range i o klasie Date.
The combination of Range
and Date
classes in Ruby on Rails is a great idea to improve code readability.
You can read about the Range class and the Date class in the documentation.