Module: PermaCache::ClassMethods

Defined in:
lib/perma_cache.rb

Instance Method Summary collapse

Instance Method Details

#perma_cache(method_name, options = {}) ⇒ Object



44
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/perma_cache.rb', line 44

def perma_cache(method_name, options = {})
  class_eval do
    define_method "#{method_name}_base_key" do
      key = []
      key << "perma_cache"
      key << "v#{PermaCache.version}"

      key << PermaCache.build_key_from_object(self)

      if options[:obj]
        key << PermaCache.build_key_from_object(send(options[:obj]))
      end

      key << method_name

      if options[:version]
        key << "v#{options[:version]}"
      end

      key = key.flatten.reject do |k|
        (k.empty? rescue nil) ||
        (k.nil? rescue nil)
      end.join('/')

      key
    end

    define_method "#{method_name}_perma_cache_key" do
      [
        send("#{method_name}_base_key"),
        (send("#{method_name}_key") rescue nil)
      ].compact.join('/').gsub(' ','_')
    end

    define_method "#{method_name}!" do
      send("#{method_name}_without_perma_cache").tap do |result|
        PermaCache.cache.write(send("#{method_name}_perma_cache_key"), result, :expires_in => options[:expires_in])
      end
    end

    define_method "#{method_name}_get_perma_cache" do
      PermaCache.cache.read(send("#{method_name}_perma_cache_key"))
    end

    define_method "#{method_name}_with_perma_cache" do
      send("#{method_name}_get_perma_cache") ||
      send("#{method_name}!")
    end

    alias_method_chain method_name, :perma_cache
  end
end