Class: ActiveRecord::Base

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

Class Method Summary collapse

Class Method Details

.cache_method(name, *args) ⇒ Object Also known as: cachethod, cachethods



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/cachethod/active_record_base_ext.rb', line 5

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

  if name.is_a?(String) || name.is_a?(Symbol)
    @methods_to_cache[name.to_sym] = args
  elsif method_name.is_a?(Array)
    cache_methods(name, *args)
  else
    raise Exception.new('Invalid first argument for cachethod method!')
  end
end

.cache_methods(names, *args) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/cachethod/active_record_base_ext.rb', line 17

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

  names.each do |name|
    @methods_to_cache[name.to_sym] = args
  end
end

.method_added(name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cachethod/active_record_base_ext.rb', line 28

def method_added name
  return if @methods_to_cache.nil? || @methods_to_cache[name].nil?

  args = @methods_to_cache.delete(name)

  define_method "#{name}_cached" do
    cache_key = "cachethod.#{self.class.to_s.underscore}-#{id}.#{name}"

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

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

.method_added_originalObject



3
# File 'lib/cachethod/active_record_base_ext.rb', line 3

alias_method :method_added_original, :method_added