Class: Kasket::Cache
- Inherits:
-
Object
- Object
- Kasket::Cache
- Defined in:
- lib/kasket/cache.rb
Instance Method Summary collapse
- #clear_local ⇒ Object
- #delete(*args) ⇒ Object
- #delete_local(*keys) ⇒ Object
- #delete_matched_local(matcher) ⇒ Object
- #get_multi(keys) ⇒ Object
-
#initialize ⇒ Cache
constructor
A new instance of Cache.
- #local ⇒ Object
- #read(*args) ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize ⇒ Cache
Returns a new instance of Cache.
3 4 5 |
# File 'lib/kasket/cache.rb', line 3 def initialize clear_local end |
Instance Method Details
#clear_local ⇒ Object
62 63 64 |
# File 'lib/kasket/cache.rb', line 62 def clear_local @local_cache = {} end |
#delete(*args) ⇒ Object
47 48 49 50 |
# File 'lib/kasket/cache.rb', line 47 def delete(*args) @local_cache.delete(args[0]) Rails.cache.delete(*args) end |
#delete_local(*keys) ⇒ Object
52 53 54 55 56 |
# File 'lib/kasket/cache.rb', line 52 def delete_local(*keys) keys.each do |key| @local_cache.delete(key) end end |
#delete_matched_local(matcher) ⇒ Object
58 59 60 |
# File 'lib/kasket/cache.rb', line 58 def delete_matched_local(matcher) @local_cache.delete_if { |k,v| k =~ matcher } end |
#get_multi(keys) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/kasket/cache.rb', line 18 def get_multi(keys) map = Hash[*keys.zip(keys.map { |key| @local_cache[key] }).flatten] missing_keys = map.select { |key, value| value.nil? }.map(&:first) unless missing_keys.empty? if Rails.cache.respond_to?(:read_multi) missing_map = Rails.cache.read_multi(missing_keys) missing_map.each do |key, value| missing_map[key] = @local_cache[key] = value end map.merge!(missing_map) else missing_keys.each do |key| map[key] = read(key) end end end map end |
#local ⇒ Object
66 67 68 |
# File 'lib/kasket/cache.rb', line 66 def local @local_cache end |
#read(*args) ⇒ Object
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/kasket/cache.rb', line 7 def read(*args) result = @local_cache[args[0]] || Rails.cache.read(*args) if result.is_a?(Array) && result.first.is_a?(String) models = get_multi(result) result = result.map { |key| models[key] } end @local_cache[args[0]] = result if result result end |
#write(key, value) ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/kasket/cache.rb', line 39 def write(key, value) if storable?(value) @local_cache[key] = value.duplicable? ? value.dup : value Rails.cache.write(key, value.duplicable? ? value.dup : value) # Fix due to Rails.cache freezing values in 2.3.4 end value end |