Class: ActiveRecord::Base

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

Class Method Summary collapse

Class Method Details

.attr_cached(*attributes) ⇒ Object

The attr_cached method should be called in the body of an ActiveRecord model which has an ‘id’ attribute.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/attr_cached.rb', line 5

def self.attr_cached *attributes
  # Assign a reusable message to raise upon the occurence of a nil id.
  missing_id = 'The \'id\' cannot be nil when calling an attribute created by attr_memcached'

  # Iterate through each attribute
  attributes.each do |attribute|
    # Set the beginning to the key to be used in both the read and write methods.
    key = "#{name.downcase}_#{attribute}_"

    # Define the method to read from the cache
    define_method attribute do
      raise missing_id if id.nil?
      Rails.cache.read(key + id.to_s)
    end

    # Define the method to write to the cache
    define_method "#{attribute}=" do |value|
      raise missing_id if id.nil?
      Rails.cache.write(key + id.to_s, value)
    end

    # Define the method to delete the attribute from the cache
    define_method "delete_#{attribute}" do
      raise missing_id if id.nil?
      Rails.cache.delete(key + id.to_s)
    end
  end
  class_name = "#{name.downcase}_"
  define_method :delete_cache do
    raise missing_id if id.nil?
    attributes.each do |attribute|
      Rails.cache.delete class_name + "#{attribute}_#{id}"
    end
  end
end