Skip to content

Instantly share code, notes, and snippets.

@jcsrb
Last active December 17, 2015 06:59
Show Gist options
  • Save jcsrb/5569905 to your computer and use it in GitHub Desktop.
Save jcsrb/5569905 to your computer and use it in GitHub Desktop.
this screams for metaprogramming
scope :created_this_hour , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_hour}' AND '#{DateTime.now.end_of_hour}'") }
scope :created_this_day , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_day}' AND '#{DateTime.now.end_of_day}'") }
scope :created_this_week , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_week}' AND '#{DateTime.now.end_of_week}'") }
scope :created_this_month , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_month}' AND '#{DateTime.now.end_of_month}'") }
scope :created_this_quarter , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_quarter}' AND '#{DateTime.now.end_of_quarter}'") }
scope :created_this_year , lambda { where("created_at BETWEEN '#{DateTime.now.beginning_of_year}' AND '#{DateTime.now.end_of_year}'") }
@goshacmd
Copy link

Why not just use a simple iterator?

[:hour, :day, :week, :month, :quarter, :year].each do |interval|
  scope "created_this_#{interval}", ->{ where(created_at: Time.now.send("beginning_of_#{interval}")..Time.now.send("end_of_#{interval}") )}
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment