Rails TimeRange

1 Comment

Say you want to query your backend objects with a range of times.

One way to do that is to define a TimeRange object which captures the time ranges you are interested in:

TimeRange.rb

class TimeRange
  def self.today
    (Time.now.midnight)..Time.now.end_of_day
  end

  def self.yesterday
    (Time.now.midnight - 1.day)..Time.now.end_of_day
  end

  def self.last_week
    (Time.now.prev_week)..Time.now.end_of_day
  end

  def self.ages_ago
    (Time.now.prev_year)..Time.now.end_of_day
  end
end

And then using these to define your ‘created_at’ parameter:

SomeController.rb

    case params[:date_posted]
    when 'today'
      created_at = TimeRange.today
    when 'yesterday'
      created_at = (Time.now.midnight - 1.day)..Time.now.end_of_day
    when 'last week'
      created_at = (Time.now.prev_week)..Time.now.end_of_day
    when 'ages ago'
      created_at = (Time.now.prev_year)..Time.now.end_of_day
    else
      logger.error "Unknown posted date on listings search #{params[:date_posted]}"
    end

which can then be used in your search:

    @attr = {
            :location => @location,
            :category_id => params[:category_id],
            :created_at => created_at
    }

    @listings = Listing.where(@attr)

Not bad!

See my previous post here for where to place your TimeRange object and how to reference it from another ruby class.

How to reference domain classes in rails

1 Comment

Working with active records in rails is nice because a lot of your domain is directly represented in your model classes.

Sometimes however, you still need to create some domain classes that aren’t tied to a database model, and reference them in your app.

I’m not sure what the best way (or convention) is for doing this, but what’s been working for me is to create a separate directory called domain

and place my domain object(s) in there:

class TimeRange
  def self.today
    (Time.now.midnight)..Time.now.end_of_day
  end

  def self.yesterday
    (Time.now.midnight - 1.day)..Time.now.end_of_day
  end

  def self.last_week
    (Time.now.prev_week)..Time.now.end_of_day
  end

  def self.ages_ago
    (Time.now.prev_year)..Time.now.end_of_day
  end
end

And then referencing them where I need them using the ‘require_relative’ command.

require_relative '../domain/time_range'
require_relative '../domain/constants'

class CitiesController < ApplicationController

%d bloggers like this: