Last active
December 12, 2015 09:39
-
-
Save ekampf/4753636 to your computer and use it in GitHub Desktop.
Add scopes to query by created_at\updated_at to models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Concerns | |
module CreatedAtScopes | |
extend ActiveSupport::Concern | |
included do | |
%w(created_at updated_at).each do |prop| | |
verb = prop.gsub('_at', '') | |
scope "#{verb}_last_h", lambda { where("#{prop} >= ?", (Time.now-1.hour).to_s(:db)) } | |
scope "#{verb}_last_6h", lambda { where("#{prop} >= ?", (Time.now-6.hour).to_s(:db)) } | |
scope "#{verb}_today", lambda { where("DATE(#{prop}) = ?", Date.today.to_s(:db)) } | |
scope "#{verb}_last7d", lambda { where("DATE(#{prop}) >= ?", (Date.today-7).to_s(:db)) } | |
scope "#{verb}_last30d", lambda { where("DATE(#{prop}) >= ?", (Date.today-30).to_s(:db)) } | |
scope "#{verb}_this_month", lambda { where("DATE(#{prop}) >= ?", Date.today.beginning_of_month.to_s(:db)) } | |
scope "#{verb}_last_6m", lambda { where("DATE(#{prop}) >= ?", (Date.today - 6.months).to_s(:db)) } | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice!
Perhaps we can make it even more dynamic by aliasing the old method_missing and add a new one that checks for Class.updated_#{integer}_#{seconds/minutes/days/months/years}_ago method (then it transforms it into the desired scope) and if it does not find it just call the original method_missing ?