Skip to content

Instantly share code, notes, and snippets.

@jewilmeer
Created May 19, 2011 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jewilmeer/980626 to your computer and use it in GitHub Desktop.
Save jewilmeer/980626 to your computer and use it in GitHub Desktop.
lambda caching
class Episode < ActiveRecord::Base
scope :airs_at_in_future, lambda{ where('episodes.airs_at > ?', Time.zone.now) }
scope :airs_at_in_past, lambda{ where('episodes.airs_at < ?', Time.zone.now) }
# will cache Time.now
scope :next_airing, airs_at_in_future.order('episodes.airs_at asc')
scope :last_aired, airs_at_in_past.order('episodes.airs_at desc')
# will not cache Time.now
scope :next_airing, lambda{ airs_at_in_future.order('episodes.airs_at asc') }
scope :last_aired, lambda{ airs_at_in_past.order('episodes.airs_at desc') }
end
@tlray
Copy link

tlray commented May 19, 2011

I guess Arel/AR only postpones (lazyloads) the sql call, and call's procs directly
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/named_scope.rb#L160

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment