Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/magic_cache_keys.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cache_key(options = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/magic_cache_keys.rb', line 28

def cache_key(options = {})
  connection.execute('SET group_concat_max_len = 1048576')
  if options[:conditions] && options[:conditions].is_a?(String) && options[:conditions].strip.upcase.starts_with?('SELECT')
    hash_sql = options[:conditions].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{cache_key_select} FROM" }
  else
    options[:select] = cache_key_select(options.delete(:order) || scope(:find, :order))
    hash_sql = construct_finder_sql(options)
  end
  
  "#{model_name.cache_key}/#{connection.select_value(hash_sql) || 'empty'}"
end

.cache_key_select(order = nil) ⇒ Object



40
41
42
# File 'lib/magic_cache_keys.rb', line 40

def cache_key_select(order = nil)
  "MD5(CONCAT(GROUP_CONCAT(CONV(#{quoted_table_name}.#{connection.quote_column_name(primary_key)},10,36)#{ ' ORDER BY ' + order unless order.blank?}), MAX(#{quoted_table_name}.#{connection.quote_column_name('updated_at')}))) as cached_key"
end

.has_many_with_cache_key(association_id, options = {}, &extension) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/magic_cache_keys.rb', line 44

def has_many_with_cache_key(association_id, options = {}, &extension)
  options[:extend] ||= []
  options[:extend] = [*options[:extend]]
  options[:extend] << ActiveRecord::CacheKeyCaching::AssociationCollectionExtension
  
  has_many_without_cache_key(association_id, options, &extension)
end

Instance Method Details

#cache_key_with_associations(*include_associations) ⇒ Object



19
20
21
22
23
24
# File 'lib/magic_cache_keys.rb', line 19

def cache_key_with_associations(*include_associations)
  parts = [cache_key_without_associations]
  include_associations.sort! {|a1, a2| a1.to_s <=> a2.to_s}
  parts += include_associations.map {|a| self.send(a).cache_key }
  parts.join('/')
end