Module: IncludeDateScopes::DefineCommonScopes

Included in:
IncludeDateScopes::DateScopes::ClassMethods
Defined in:
lib/include_date_scopes/define_common_scopes.rb

Instance Method Summary collapse

Instance Method Details

#define_common_scopes(prefix, column_name) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/include_date_scopes/define_common_scopes.rb', line 4

def define_common_scopes(prefix, column_name)
  define_singleton_method :"#{prefix}day" do |day|
    __send__(:"#{prefix}on", day)
  end

  define_singleton_method :"#{prefix}today" do
    __send__(:"#{prefix}on", Date.today)
  end

  define_singleton_method :"#{prefix}yesterday" do
    __send__(:"#{prefix}on", Date.yesterday)
  end

  define_singleton_method :"#{prefix}tomorrow" do
    __send__(:"#{prefix}on", Date.tomorrow)
  end

  [:day, :week, :month, :year].each do |time_unit|
    define_singleton_method :"#{prefix}next_#{time_unit}" do
      now = Time.now
      __send__(:"#{prefix}between", now, now + 1.send(time_unit))
    end
    define_singleton_method :"#{prefix}last_#{time_unit}" do
      now = Time.now
      __send__(:"#{prefix}between", now - 1.send(time_unit), now + 1.second)
    end
    define_singleton_method :"#{prefix}next_n_#{time_unit}s" do |count|
      now = Time.now
      __send__(:"#{prefix}between", now, now + count.send(time_unit))
    end
    define_singleton_method :"#{prefix}last_n_#{time_unit}s" do |count|
      now = Time.now
      __send__(:"#{prefix}between", now - count.send(time_unit), now + 1.second)
    end
  end

  define_singleton_method :"#{prefix}last_30_days" do
    __send__(:"#{prefix}last_n_days", 30)
  end

  define_singleton_method :"#{prefix}most_recent" do
    order("#{column_name} desc")
  end
end