Module: TemporalScopes::HasTemporalScopes::ClassMethods

Defined in:
lib/temporal_scopes/has_temporal_scopes.rb

Overview

The following class methods and scopes are added to ActiveRecord::Base classes that have been called has_temporal_scopes on.

Instance Method Summary collapse

Instance Method Details

#nowActiveRecord::Relation

Filters for only current objects.

This is the default scope.

Returns:

  • (ActiveRecord::Relation)

    only current objects.



74
75
76
77
78
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 74

def now
  without_temporal_condition
  .where(arel_table[:valid_from].eq(nil).or(arel_table[:valid_from].lteq(Time.zone.now)))
  .where(arel_table[:valid_to].eq(nil).or(arel_table[:valid_to].gteq(Time.zone.now)))
end

#pastActiveRecord::Relation

Filters for only past objects.

Examples:

Getting only archived articles by an author.

author.articles.past

Returns:

  • (ActiveRecord::Relation)

    only past objects.



87
88
89
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 87

def past
  without_temporal_condition.where('valid_to < ?', Time.zone.now)
end

#with_pastActiveRecord::Relation

Removes the filters such that past and present objects are returned.

Returns:

  • (ActiveRecord::Relation)

    past and current objects.



96
97
98
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 96

def with_past
  without_temporal_condition
end

#without_temporal_conditionActiveRecord::Relation

Removes temporal conditions from the query.

Examples:

Article.where(valid_to: 10.days.ago..1.day.ago)                             # => []  (due to default scope.)
Article.without_temporal_condition.where(valid_to: 10.days.ago..1.day.ago)  # returns the desired articles.

Returns:

  • (ActiveRecord::Relation)

    the relation without temporal conditions on valid_from and valid_to.



60
61
62
63
64
65
66
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 60

def without_temporal_condition
  relation = rewhere(valid_from: nil, valid_to: nil)
  relation.where_values.delete_if { |query| 
    query.to_sql.include?("\"valid_from\"") || query.to_sql.include?("\"valid_to\"") 
  } 
  relation
end