Module: ActiveRecordCache::Base::ClassMethods

Defined in:
lib/activerecord_cache/base.rb

Instance Method Summary collapse

Instance Method Details

#cache_key(id_or_record) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/activerecord_cache/base.rb', line 14

def cache_key(id_or_record)
  unless use_activerecord_cache
    message = "ActiveRecord cache is not enabled for #{self.name}"
    raise ActiveRecordCache::CacheNotEnabled, message
  end

  if id_or_record.is_a?(ActiveRecord::Base)
    id = id_or_record[id_or_record.class.primary_key]
  else
    id = id_or_record
  end

  "#{model_name}/#{id}"
end

#find_in_cache(id) ⇒ Object



75
76
77
78
79
80
81
82
# File 'lib/activerecord_cache/base.rb', line 75

def find_in_cache(id)
  unless use_activerecord_cache
    message = "ActiveRecord cache is not enabled for #{self.name}"
    raise ActiveRecordCache::CacheNotEnabled, message
  end

  Rails.cache.read(cache_key(id))
end

#find_some_through_cache(ids) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/activerecord_cache/base.rb', line 46

def find_some_through_cache(ids)
  unless use_activerecord_cache
    message = "ActiveRecord cache is not enabled for #{self.name}"
    raise ActiveRecordCache::CacheNotEnabled, message
  end

  records = []
  cache_misses = []

  ids.each do |id|
    if record = find_in_cache(id)
      records << record
    else
      cache_misses << id
    end
  end

  if cache_misses.present?
    # use where to bypass cached finders
    loaded_records = where(primary_key => cache_misses).load

    loaded_records.each(&:write_to_cache)

    records += loaded_records
  end

  records
end

#find_through_cache(id) ⇒ Object



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

def find_through_cache(id)
  unless use_activerecord_cache
    message = "ActiveRecord cache is not enabled for #{self.name}"
    raise ActiveRecordCache::CacheNotEnabled, message
  end

  record = Rails.cache.read(cache_key(id))

  unless record
    # use where to bypass cached finders
    record = where(primary_key => id).first
    record.write_to_cache if record
  end

  record
end