Module: GenCache::AttributeCache

Included in:
Caches
Defined in:
lib/gen_cache/cache_types/attribute_cache.rb

Instance Method Summary collapse

Instance Method Details

#with_attribute(*attributes) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/gen_cache/cache_types/attribute_cache.rb', line 3

def with_attribute(*attributes)
  self.cached_indices ||= {}
  self.cached_indices = self.cached_indices.merge(attributes.each_with_object({}) {
    |attribute, indices| indices[attribute] = {}
  })

  attributes.each do |attribute|
    define_singleton_method("find_cached_by_#{attribute}") do |value|
      self.cached_indices["#{attribute}"] ||= []
      self.cached_indices["#{attribute}"] << value
      cache_key = GenCache.attribute_key(self, attribute, value)
      GenCache.fetch(cache_key) do
        self.send("find_by_#{attribute}", value)
      end
    end

    define_singleton_method("find_cached_all_by_#{attribute}") do |value|
      self.cached_indices["#{attribute}"] ||= []
      self.cached_indices["#{attribute}"] << value
      cache_key = GenCache.attribute_key(self, attribute, value, all: true)
      GenCache.fetch(cache_key) do
        self.send("find_all_by_#{attribute}", value)
      end
    end
  end
end