Module: CacheMachine::Cache::ClassMethods

Defined in:
lib/cache_machine/cache.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_cache_machine_for(*associations) ⇒ Object Also known as: cache_map

Initializes tracking associations to write and reset cache.

Examples:

Cache associated collections.

acts_as_cache_machine_for :cats, :dogs

Cache result of method to be expired when collection changes.

acts_as_cache_machine_for :cats => :cat_ids

Cache and expire dependent collections (mouse change invalidates all other collection caches by chain)

acts_as_cache_machine_for :mouses => :cats, :cats => [:dogs, :bears], :dogs, :bears

Parameters:

  • associations (Hash<Symbol, Array>)

    Cache Map



60
61
62
63
64
65
# File 'lib/cache_machine/cache.rb', line 60

def acts_as_cache_machine_for *associations
  Time.zone ||= ActiveSupport::TimeZone[0]

  include CacheMachine::Cache::Map
  cache_associated(associations)
end

#reset_timestamp(format = nil) ⇒ Object

Resets timestamp of class collection.

Parameters:

  • format (Symbol) (defaults to: nil)


104
105
106
107
108
# File 'lib/cache_machine/cache.rb', line 104

def reset_timestamp format = nil
  cache_key = timestamp_key format
  CacheMachine::Logger.info "CACHE_MACHINE (reset_timestamp): deleting '#{cache_key}'."
  Rails.cache.delete(cache_key)
end

#reset_timestampsObject

Resets all timestams for all formats.



111
112
113
# File 'lib/cache_machine/cache.rb', line 111

def reset_timestamps
  CacheMachine::Cache.formats.each { |format| reset_timestamp format }
end

#timestamp(format = nil) ⇒ String

Returns timestamp of class collection.

Examples:

Return timestamp of the class.

MyActiveRecordClass.timestamp

Parameters:

  • format (Symbol) (defaults to: nil)

Returns:

  • (String)


76
77
78
# File 'lib/cache_machine/cache.rb', line 76

def timestamp format = nil
  Rails.cache.fetch(timestamp_key format) { Time.now.to_i.to_s }
end

#timestamp_key(format = nil) ⇒ String

Returns cache key to fetch timestamp from memcached.

Parameters:

  • format (Symbol) (defaults to: nil)

Returns:

  • (String)


85
86
87
# File 'lib/cache_machine/cache.rb', line 85

def timestamp_key format = nil
  [self.name, format, 'timestamp'].join '_'
end

#timestamped_key(format = nil) ⇒ String

Returns cache key of anything with timestamp attached.

Examples:

Return timestamped key of the class.

MyActiveRecordClass.timestamped_key

Parameters:

  • format (Symbol) (defaults to: nil)

Returns:

  • (String)


97
98
99
# File 'lib/cache_machine/cache.rb', line 97

def timestamped_key format = nil
  [timestamp_key(format), timestamp(format)].join '_'
end