pixelearth
pixelearth

Reputation: 14610

Is there a ruby/rails gem that makes scoping dates easy

anyone know of a gem that makes scoping dates easy? I'd love to do Model.this_year(:created_at).where()... etc. Thought I heard of one once.

I was thinking something along the lines of dues_paid_this_year or updated_at_two_hours_ago. A gem that could do this like search_logic by creating dynamic scopes would make my world lovely

Upvotes: 4

Views: 415

Answers (2)

Callmeed
Callmeed

Reputation: 4992

I don't know of a gem–although it would be very cool to create one. That being said, this would probably get you by:

class Thing < ActiveRecord::Base
  # Some date-related scopes
  scope :today, where("created_at > ?", Time.now.beginning_of_day)
  scope :yesterday, where("created_at < ? and created_at > ?", 1.day.ago.end_of_day, 1.day.ago.beginning_of_day)
  scope :this_month, where("created_at > ?", Time.now.beginning_of_month)
  scope :last_month, where("created_at < ? and created_at > ?", 1.month.ago.end_of_month, 1.month.ago.beginning_of_month)
  scope :this_year, where("created_at > ?", Time.now.beginning_of_year)
  ### 
  # All your model stuff goes here
  ###

  # Let's get real tricky with method_missing 
  # and allow Thing.last_X_days for work for any value of X
  private

  def self.method_missing(method, *args, &block) 
    if method.to_s =~  /^last_(\d+)_days$/i
      days = method.to_s.match(/^last_(\d+)_days$/i)
      return self.where("created_at > ?", days[1].to_i.days.ago.beginning_of_day)
    else
      super
    end
  end   

end

This will give you some basic scopes like Thing.this_month ... plus a dynamic finder that will let you do something like Thing.last_90_days and work for any number (WARNING: I'm a bit of a method_missing n00b, the code worked for me but maybe someone can double-check it).

FYI I'm assuming Rails 3 here.

Upvotes: 2

allesklar
allesklar

Reputation: 9580

Can't you do what you want with lambda scopes?

Upvotes: 0

Related Questions