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.



72
73
74
75
76
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 72

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.



85
86
87
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 85

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.



94
95
96
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 94

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
# File 'lib/temporal_scopes/has_temporal_scopes.rb', line 60

def without_temporal_condition
  relation = unscope(where: [:valid_from, :valid_to]) 
  relation.where_values.delete_if { |query| query.to_sql.include?("\"valid_from\"") || query.to_sql.include?("\"valid_to\"") } if relation && relation.where_values
  relation
end