Module: LastModCache::RelationCache

Defined in:
lib/last_mod_cache.rb

Overview

Module added to ActiveRecord::Relation to add the with_cache method.

Instance Method Summary collapse

Instance Method Details

#first_with_cache(cache_options = nil) ⇒ Object

Add first_with_cache to the end of a relation chain to perform the find and store the results in cache. Options for cache storage can be set with the optional cache_options parameter. This method is equivalent to calling first on the relation so that no more relations can be chained after it is called.

Example:

Blog.where(:name => "My Blog").first_with_cache

Raises:

  • (NotImplementedError)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/last_mod_cache.rb', line 50

def first_with_cache(cache_options = nil)
  raise NotImplementedError.new("LastModCache is not available on #{klass}") unless klass.include?(LastModCache)
  limited_scope = limit(1)
  conn = klass.connection
  key_scope = limited_scope.select(["#{conn.quote_table_name(klass.table_name)}.#{conn.quote_column_name(klass.primary_key)} AS #{conn.quote_column_name('id')}", "#{conn.quote_table_name(klass.table_name)}.#{conn.quote_column_name(klass.updated_at_column)} AS #{conn.quote_column_name('updated_at')}"])
  bind_variables = limited_scope.respond_to?(:bind_values) ? limited_scope.bind_values.collect{|column, value| column.type_cast(value)} : []
  Proxy.new do
    id, timestamp = klass.send(:id_and_updated_at, :sql => key_scope.to_sql, :bind_values => bind_variables)
    record = last_mod_cache.fetch(klass.send(:updated_at_cache_key, :first_with_cache, {:sql => limited_scope.to_sql, :bind_values => bind_values}, timestamp), cache_options) do
      limited_scope.where(klass.primary_key => id).first if id
    end
    record.freeze if record
  end
end

#with_cache(cache_options = nil) ⇒ Object

Add with_cache to the end of a relation chain to perform the find and store the results in cache. Options for cache storage can be set with the optional cache_options parameter. This method is equivalent to calling to_a on the relation so that no more relations can be chained after it is called.

Example:

BlogPosts.where(:blog_id => my_blog.id).order("published_at DESC").limit(20).with_cache

Raises:

  • (NotImplementedError)


35
36
37
38
39
40
41
# File 'lib/last_mod_cache.rb', line 35

def with_cache(cache_options = nil)
  raise NotImplementedError.new("LastModCache is not available on #{klass}") unless klass.include?(LastModCache)
  bind_variables = respond_to?(:bind_values) ? bind_values.collect{|column, value| column.type_cast(value)} : []
  klass.all_with_cache(:sql => to_sql, :bind_values => bind_variables, :cache => cache_options) do
    to_a
  end
end