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.
Filed under: programming, rails Tagged: domain, rails, RoR, ruby on rails, rubyonrails