Class: Arel::Middleware::CacheAccessor

Inherits:
Object
  • Object
show all
Defined in:
lib/arel/middleware/cache_accessor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ CacheAccessor

Returns a new instance of CacheAccessor.



6
7
8
# File 'lib/arel/middleware/cache_accessor.rb', line 6

def initialize(cache)
  @cache = cache
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



4
5
6
# File 'lib/arel/middleware/cache_accessor.rb', line 4

def cache
  @cache
end

Instance Method Details

#cache_key(sql) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/arel/middleware/cache_accessor.rb', line 25

def cache_key(sql)
  # An important aspect of this cache key method is that it includes hashes of all active
  # middlewares. If multiple Arel middleware chains that are using the same cache backend,
  # this cache key mechanism will prevent cache entries leak in the wrong chain.

  active_middleware_cache_key = Arel.middleware.current.map(&:hash).join('&') || 0
  active_middleware_cache_key + '|' + cache_key_for_sql(sql)
end

#cache_key_for_sql(sql) ⇒ Object



21
22
23
# File 'lib/arel/middleware/cache_accessor.rb', line 21

def cache_key_for_sql(sql)
  Digest::SHA256.hexdigest(sql)
end

#read(original_sql) ⇒ Object



10
11
12
# File 'lib/arel/middleware/cache_accessor.rb', line 10

def read(original_sql)
  cache.read cache_key(original_sql)
end

#write(transformed_sql:, transformed_binds:, original_sql:, original_binds:) ⇒ Object



14
15
16
17
18
19
# File 'lib/arel/middleware/cache_accessor.rb', line 14

def write(transformed_sql:, transformed_binds:, original_sql:, original_binds:)
  # To play it safe, the order of binds was changed and therefore we won't reuse the query
  return if transformed_binds != original_binds

  cache.write(cache_key(original_sql), transformed_sql)
end