Module: Cacheable::ClassMethodCache

Included in:
Caches
Defined in:
lib/cacheable/types/class_method_cache.rb

Instance Method Summary collapse

Instance Method Details

#with_class_method(*methods) ⇒ Object

Cached class method Should expire on any instance save



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/cacheable/types/class_method_cache.rb', line 5

def with_class_method(*methods)
  self.cached_class_methods = methods.each_with_object({}) { |meth, indices| indices[meth] = [] }

  class_eval do
    after_commit :expire_class_method_cache, on: :update
  end

  methods.each do |meth|
    define_singleton_method("cached_#{meth}") do |*args|
      self.cached_class_methods["#{meth}"] ||= []
      self.cached_class_methods["#{meth}"] << args
      Cacheable.fetch class_method_cache_key(meth, args) do
        self.method(meth).arity == 0 ? send(meth) : send(meth, *args)
      end
    end
  end
end