Module: Switchman::ActiveRecord::QueryCache

Defined in:
lib/switchman/active_record/query_cache.rb

Instance Method Summary collapse

Instance Method Details

#cacheObject



31
32
33
34
35
36
37
# File 'lib/switchman/active_record/query_cache.rb', line 31

def cache
  old, self.query_cache_enabled = query_cache_enabled, true
  yield
ensure
  self.query_cache_enabled = old
  clear_query_cache unless self.query_cache_enabled
end

#clear_query_cacheObject



46
47
48
# File 'lib/switchman/active_record/query_cache.rb', line 46

def clear_query_cache
  Thread.current[:query_cache].try(:clear)
end

#disable_query_cache!Object



27
28
29
# File 'lib/switchman/active_record/query_cache.rb', line 27

def disable_query_cache!
  self.query_cache_enabled = false
end

#enable_query_cache!Object

basically wholesale repeat of the methods from the original (see github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb), but with self.query_cache_enabled and self.query_cache_enabled= instead of @query_cache_enabled.



23
24
25
# File 'lib/switchman/active_record/query_cache.rb', line 23

def enable_query_cache!
  self.query_cache_enabled = true
end

#query_cacheObject

thread local accessors to replace @query_cache_enabled



5
6
7
8
# File 'lib/switchman/active_record/query_cache.rb', line 5

def query_cache
  thread_cache = Thread.current[:query_cache] ||= {}
  thread_cache[self.object_id] ||= Hash.new { |h,sql| h[sql] = {} }
end

#query_cache_enabledObject



10
11
12
# File 'lib/switchman/active_record/query_cache.rb', line 10

def query_cache_enabled
  Thread.current[:query_cache_enabled]
end

#query_cache_enabled=(value) ⇒ Object



14
15
16
# File 'lib/switchman/active_record/query_cache.rb', line 14

def query_cache_enabled=(value)
  Thread.current[:query_cache_enabled] = value
end

#select_all(arel, name = nil, binds = [], preparable: nil) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/switchman/active_record/query_cache.rb', line 50

def select_all(arel, name = nil, binds = [], preparable: nil)
  if self.query_cache_enabled && !locked?(arel)
    arel, binds = binds_from_relation(arel, binds)
    sql = to_sql(arel, binds)
    if ::Rails.version >= '5'
      cache_sql(sql, binds) { super(sql, name, binds, preparable: visitor.preparable) }
    else
      cache_sql(sql, binds) { super(sql, name, binds) }
    end
  else
    if ::Rails.version >= '5'
      super
    else
      super(arel, name, binds)
    end
  end
end

#uncachedObject



39
40
41
42
43
44
# File 'lib/switchman/active_record/query_cache.rb', line 39

def uncached
  old, self.query_cache_enabled = query_cache_enabled, false
  yield
ensure
  self.query_cache_enabled = old
end