Module: Cachengue::Caching

Defined in:
lib/cachengue/caching.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clear(classx) ⇒ Object



37
38
39
40
41
# File 'lib/cachengue/caching.rb', line 37

def clear(classx)
  return if Rails.env.test?

  keys(classx).map { |k| Rails.cache.delete(k) }.size
end

.fetch(classx, method_name, args) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cachengue/caching.rb', line 43

def fetch(classx, method_name, args)
  key = Cachengue::Caching.key_by(classx, method_name, args)

  new_block = proc do
    value = yield(*args)

    if defined?(::ActiveRecord) && value.is_a?(::ActiveRecord::Relation)
      value.to_a
    else
      value
    end
  end

  Rails.cache.fetch(key, &new_block)
end

.key_by(classx, method_name, args) ⇒ Object



21
22
23
24
25
# File 'lib/cachengue/caching.rb', line 21

def key_by(classx, method_name, args)
  args = args.map(&:as_json)

  "#{key_prefix(classx)}:#{method_name}:#{args}"
end

.key_prefix(classx) ⇒ Object



27
28
29
# File 'lib/cachengue/caching.rb', line 27

def key_prefix(classx)
  "cache:#{classx.to_s.underscore}"
end

.keys(classx) ⇒ Object



31
32
33
34
35
# File 'lib/cachengue/caching.rb', line 31

def keys(classx)
  prefix = Cachengue::Caching.key_prefix(classx)

  Rails.cache.data.keys("#{prefix}:*")
end

Instance Method Details

#cachengue(method_name = nil, &block) ⇒ Object



5
6
7
8
9
# File 'lib/cachengue/caching.rb', line 5

def cachengue(method_name = nil, &block)
  return Cachengue::Proxy.new(self) if method_name.blank?

  fetch(self, method_name, [], &block)
end

#module_cachengue(method_name, &block) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/cachengue/caching.rb', line 11

def module_cachengue(method_name, &block)
  singleton_class.instance_eval do
    define_method(method_name) do |*args|
      Cachengue::Caching.fetch(self, method_name, args, &block)
    end
  end
end