Module: Cachetastic::Cacheable

Included in:
ActiveRecord::Base
Defined in:
lib/gems/cachetastic-2.1.2/lib/cachetastic/cacheable.rb,
lib/gems/cachetastic-2.1.2/lib/cachetastic.rb

Overview

Include this module into an Object to achieve simplistic Object level caching.

Example:

class Person
  include Cachetastic::Cacheable

  attr_accessor :name

  def cachetastic_key
    self.name
  end

  def always_the_same(x, y)
    cacher("always_the_same") do
      x + y
    end
  end

end

Defined Under Namespace

Modules: ClassAndInstanceMethods, ClassOnlyMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object




174
175
176
177
178
# File 'lib/gems/cachetastic-2.1.2/lib/cachetastic/cacheable.rb', line 174

def self.included(klass) # :nodoc:
  klass.send(:include, ClassAndInstanceMethods)
  klass.extend(ClassOnlyMethods)
  klass.extend(ClassAndInstanceMethods)
end

Instance Method Details

#cache_selfObject

Unless the object’s cachetastic_key method returns nil this method will store the object in the cache using the object’s cachetastic_key as the key. You MUST create an instance level method called cachetastic_key and have it return a valid key! If you return nil from the cachetastic_key method or you will not be able to use the cache_self and uncache_self methods.

Example:

class Person
  include Cachetastic::Cacheable
  attr_accessor :name
  def cachetastic_key
    self.name
  end
end

Person.get_from_cache("Mark Bates") # => nil
p = Person.new
p.name = "Mark Bates"
p.cache_self
Person.get_from_cache("Mark Bates") # => "Mark Bates"


142
143
144
# File 'lib/gems/cachetastic-2.1.2/lib/cachetastic/cacheable.rb', line 142

def cache_self
  cache_class.set(self.cachetastic_key, self) unless self.cachetastic_key.nil?
end

#uncache_selfObject

Unless the object’s cachetastic_key method returns nil this method will delete the object in the cache using the object’s cachetastic_key as the key. You MUST create an instance level method called cachetastic_key and have it return a valid key! If you return nil from the cachetastic_key method or you will not be able to use the cache_self and uncache_self methods.

Example:

class Person
  include Cachetastic::Cacheable
  attr_accessor :name
  def cachetastic_key
    self.name
  end
end

Person.get_from_cache("Mark Bates") # => nil
p = Person.new
p.name = "Mark Bates"
p.cache_self
Person.get_from_cache("Mark Bates") # => "Mark Bates"
p.uncache_self
Person.get_from_cache("Mark Bates") # => nil


168
169
170
# File 'lib/gems/cachetastic-2.1.2/lib/cachetastic/cacheable.rb', line 168

def uncache_self
  cache_class.delete(self.cachetastic_key) unless self.cachetastic_key.nil?
end