Module: TimestampScopes::ClassMethods

Defined in:
lib/timestamp_scopes.rb

Instance Method Summary collapse

Instance Method Details

#add_timestamp_scopes(*args) ⇒ Object

Adds scopes for the given timestamp columns. For each symbol given, creates a timestamp scope of the same name. The timestamp scope will default to reference a column of the same name, but with a suffix of “_at”. So, if :created is passed, then a .created scope will be made, which adds conditions to the :created_at column. If no args are passed, then timestamp scopes will be created for the default timestamp columns, :created_at and updated_at.



20
21
22
23
24
25
# File 'lib/timestamp_scopes.rb', line 20

def add_timestamp_scopes(*args)
  args << :created << :updated if args.empty?
  args.each do |scope_name|
    define_timestamp_scope(scope_name)
  end
end

#define_timestamp_scope(scope_name, column_name = nil) ⇒ Object

Add a class method name “scope_name”, which handles the before and after timestamp scoping DSLs.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/timestamp_scopes.rb', line 29

def define_timestamp_scope(scope_name, column_name = nil)
  column_name ||= scope_name.to_s + '_at'

  define_singleton_method(scope_name) do |options|
    options ||= {}

    ops = {
      after:  '>',
      before: '<',
    }

    relation = scoped

    options.each do |op, time|
      relation = relation.where("#{column_name} #{ops[op]} ?", time)
    end

    relation
  end

end