Skip to content

Instantly share code, notes, and snippets.

@gautamrege
Created October 18, 2011 07:41
Show Gist options
  • Save gautamrege/1294830 to your computer and use it in GitHub Desktop.
Save gautamrege/1294830 to your computer and use it in GitHub Desktop.
Frozen values in scope and chained scopes
=begin
'frozen' value for end_at in scope :active
The same frozen value is propogated to :national scope!
The Time.now will be set to the first time the scope is evaluated.
This is explained at http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
* NON-WORKING SOLUTION *
=end
class Something
scope :active, where('end_at > ?', Time.now)
scope :national, where(:is_national => true).active
end
=begin
Here the Time.now value is always re-evaluated because of the lambda.
HOWEVER, :active is chained in :national and so here:
+ scope active will keep re-evaluating the Time.now
+ scope national will NOT evalute the Time.now from active and keep end_at frozen to when
it was first evaluated!
* NON-WORKING SOLUTION *
=end
class Something
scope :active, lambda { where('end_at > ?',Time.now) }
scope :national, where(:is_national => true).active
end
=begin
This is the right fix where we add a lambda EVEN for :national scope so that it re-evaluates
everytime for the sake of :active scope!
** WORKING SOLUTION **
=end
class Something
scope :active, lambda { where('end_at > ?',Time.now) }
scope :national, lambda { where(:is_national => true).active }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment