Module: Cachethod::ClassMethods

Defined in:
lib/cachethod.rb

Instance Method Summary collapse

Instance Method Details

#cache_class_method(names, *args) ⇒ Object Also known as: cache_class_methods



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/cachethod.rb', line 7

def cache_class_method names, *args
  [*names].each do |name|
    define_singleton_method "#{name}_cached" do
      cache_key = "cachethod.#{self.class.to_s.underscore}.self."
      cache_key += "#{hash}.#{name}."
      cache_key += args.hash.to_s

      Rails.cache.fetch(cache_key, *args) do
        send("#{name}!")
      end
    end

    self.singleton_class.send(:alias_method, "#{name}!", name)
    self.singleton_class.send(:alias_method, name, "#{name}_cached")
  end
end

#cache_method(names, *args) ⇒ Object Also known as: cache_methods, cachethod, cachethods



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/cachethod.rb', line 24

def cache_method names, *args
  @methods_to_cache ||= {}

  [*names].each do |name|
    if instance_methods.include?(name.to_sym)
      cache_method_create(name, *args)
    else
      @methods_to_cache[name.to_sym] = args
    end
  end
end

#cache_method_create(name, *args) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/cachethod.rb', line 48

def cache_method_create name, *args
  define_method "#{name}_cached" do
    cache_key = "cachethod.#{self.class.to_s.underscore}."
    cache_key += "#{hash}.#{name}."
    cache_key += args.hash.to_s

    Rails.cache.fetch(cache_key, *args) do
      send("#{name}!")
    end
  end

  alias_method "#{name}!", name
  alias_method name, "#{name}_cached"
end

#method_added(name) ⇒ Object



41
42
43
44
45
46
# File 'lib/cachethod.rb', line 41

def method_added name
  super
  return if @methods_to_cache.nil? || @methods_to_cache[name].nil?
  args = @methods_to_cache.delete(name)
  cache_method_create(name, *args)
end