Skip to content

Instantly share code, notes, and snippets.

@JackDanger
Created September 25, 2009 00:44
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 JackDanger/193177 to your computer and use it in GitHub Desktop.
Save JackDanger/193177 to your computer and use it in GitHub Desktop.
# This works alright, I wouldn't use it without testing first though.
module KeepsCachedRecords
def self.included(base)
base.extend ClassMethods
class << base
alias_method_chain :find_one, :cached_records
alias_method_chain :find_some, :cached_records
alias_method_chain :find_every, :cached_records
end
end
module ClassMethods
def find_every_with_cached_records(options = {}, &block)
if use_cached_records?(options)
cached_records
else
find_every_without_cached_records(options, &block)
end
end
def find_one_with_cached_records(id, options = {}, &block)
if use_cached_records?(options)
cached_records.find {|record| id == record.id }
else
find_one_without_cached_records(id, options, &block)
end
end
def find_some_with_cached_records(ids, options = {}, &block)
if use_cached_records?(options)
cached_records.select {|record| ids.include?(record.id) }
else
find_some_without_cached_records(ids, options, &block)
end
end
protected
# retrieve cached records. returns nil unless
# keeps_cached_records is called in the class
attr_accessor :cached_records
def use_cached_records?(options)
options.values.compact.blank? && !cached_records.blank?
end
def keeps_cached_records
@cached_records = Array(all)
end
end
end
ActiveRecord::Base.send :include, KeepsCachedRecords
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment