Module: CacheHelper

Included in:
ActiveRecord::Base
Defined in:
lib/cache_helper.rb,
lib/cache_helper/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



2
3
4
5
# File 'lib/cache_helper.rb', line 2

def self.included(base)
  base.alias_method_chain :cache_key, :new_record_id
  base.extend(ClassMethods)
end

Instance Method Details

#association_updated_time(association) ⇒ Object

Returns the latest updated time of the record or records in the specified association. This can be used as a method_cache_key option if the method’s return value depends on the associated records.

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cache_helper.rb', line 45

def association_updated_time(association)
  self.class.reflect_on_all_associations.each do |assoc_reflection|
    if (assoc_reflection.name == association)
      case assoc_reflection.macro
      when :has_one, :belongs_to
        return self.__send__(association).updated_at
      when :has_many, :has_and_belongs_to_many
        return self.__send__(association).maximum(:updated_at)
      end
    end
  end
  raise ArgumentError.new("association #{association.inspect} not found in #{self.class.name}")
end

#cache_key_with_new_record_idObject

Overrides ActiveRecord::Base#cache_key to return unique cache keys for new records.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/cache_helper.rb', line 9

def cache_key_with_new_record_id
  key = cache_key_without_new_record_id
  if self.new_record?
    # The object is not yet database-backed; append the object's ID and the
    # current time to use as a provisional cache key.
    if @temp_cache_key.nil?
      @temp_cache_key = key << "(#{self.__id__})-#{Time.now.to_s(:number)}"
    else
      key = @temp_cache_key
    end
  end
  key
end

#method_cache_key(method, options = {}) ⇒ Object

Returns a cache key associated with the record for the specified method and options.



25
26
27
28
29
# File 'lib/cache_helper.rb', line 25

def method_cache_key(method, options = {})
  key = self.cache_key + "-#{method.to_s}"
  key << ".#{options.hash.to_s(36)}" unless options.empty?
  key
end

#method_cache_key_using_associations(method, *remaining_args) ⇒ Object

Returns a cache key associated with the record for the specified method, associations, and options.



33
34
35
36
37
38
39
40
# File 'lib/cache_helper.rb', line 33

def method_cache_key_using_associations(method, *remaining_args)
  options = remaining_args.extract_options!
  associations = remaining_args
  associations.each do |association|
    options["#{association.to_s}_updated_time".to_sym] = association_updated_time(association)
  end
  method_cache_key(method, options)
end