Module: CacheKeyForHelper

Included in:
CacheKeyForViewHelper
Defined in:
lib/cache_key_for/cache_key_for_helper.rb

Overview

“‘ app_name:views/en/datacenters/5bd92bd352e7726d02175752913014711f5d412e/companies/1-20150619101645935901000/2015-06-26/7a6f89a738006a69c1d1e0214e147bab “`

Instance Method Summary collapse

Instance Method Details

#cache_key_for(scoped_collection, collection_prefix, cache_owner_cache_key = '', suffix = '', whitelist_params = [], default_params = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/cache_key_for/cache_key_for_helper.rb', line 45

def cache_key_for(scoped_collection, collection_prefix, cache_owner_cache_key = '', suffix = '', whitelist_params = [], default_params = {})
  if scoped_collection.respond_to?(:maximum) # ActiveRecord
    begin
      max_updated_at = scoped_collection.maximum(scoped_collection.table_name + '.updated_at').to_f
    # can't use join table as query root if query includes polimorphic associations
    rescue ActiveRecord::EagerLoadPolymorphicError
      Rails.logger.debug "[CacheKeyForHelper] Fallback to array (ActiveRecord::EagerLoadPolymorphicError)"
      scoped_collection = scoped_collection.to_a
      max_updated_at = scoped_collection.to_a.map { |i| i.updated_at ? i.updated_at.utc.to_f : 0 }.max
    end
  elsif scoped_collection.class == Array
    max_updated_at = scoped_collection.to_a.map { |i| i.updated_at ? i.updated_at.utc.to_f : 0 }.max
  elsif scoped_collection.respond_to?(:max) # Mongoid
    max_updated_at = scoped_collection.max(:updated_at).to_f
  end
  count = scoped_collection.count
  if scoped_collection.respond_to?(:ids)
    ids_string = scoped_collection.ids
  else
    ids_string = scoped_collection.to_a.map(&:id).join('-')
  end
  blacklist_params = ['utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign']
  request_params = if request.params
    if whitelist_params.empty?
      default_params.merge(request.params).reject { |k, _v| blacklist_params.map(&:to_s).include?(k.to_s) }
    else
      default_params.merge(request.params).select { |k, _v| whitelist_params.map(&:to_s).include?(k.to_s) }
    end.map { |k, v| [k.to_s.dup.force_encoding('UTF-8'), v.dup.to_s.force_encoding('UTF-8')] }
  else
    nil
  end
  digest = Digest::SHA1.hexdigest("#{ids_string}-#{max_updated_at}-#{count}-#{request.subdomains.join('.')}-#{request.path}-#{request_params}")
  # puts "Caller: #{caller.first}"
  # puts "generated cache key digest base: #{ids_string}-#{max_updated_at}-#{count}-#{request.subdomains.join('.')}-#{request.path}-#{request_params}"
  # puts "generated cache key: #{I18n.locale}/#{collection_prefix}/#{digest}/#{cache_owner_cache_key}/#{suffix}"
  "#{I18n.locale}/#{collection_prefix}/#{digest}/#{cache_owner_cache_key}/#{suffix}"
end