Time range operations with Rails

Returning basic time ranges using ActiveSupport methods.

How many times you needed to return a specific time range in order to use it on a query?

I was used to code like this in order to get the time range:

range = Date.yesterday.beginning_of_day..Date.yesterday.end_of_day
User.where(created_at: range)

Fortunately I’ve found a beautiful way to solve this without such redundancy!

ActiveSupport has many different methods to deal with time ranges:

User.where(created_at: 1.day.ago.all_day)
User.where(created_at: 1.week.ago.all_week)
User.where(created_at: 2.months.ago.all_month)
User.where(created_at: 3.years.ago.all_year)
User.where(created_at: 4.months.ago.all_quarter)

Rails stills surprises me after years working with it. That’s why it’s a real pleasure to use it daily!

Keep coding ;)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.