Module: SecondLevelCache::ActiveRecord::FinderMethods

Defined in:
lib/second_level_cache/active_record/finder_methods.rb

Instance Method Summary collapse

Instance Method Details

#find_one(id) ⇒ Object

TODO: find_some api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_one

Cacheable:

current_user.articles.where(status: 1).visiable.find(params[:id])

Uncacheable:

Article.where("user_id = '1'").find(params[:id])
Article.where("user_id > 1").find(params[:id])
Article.where("articles.user_id = 1").find(prams[:id])
Article.where("user_id = 1 AND ...").find(params[:id])


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/second_level_cache/active_record/finder_methods.rb', line 19

def find_one(id)
  return super unless cachable?

  id = id.id if ActiveRecord::Base == id
  record = @klass.read_second_level_cache(id)
  return record if record && where_values_match_cache?(record)

  record = super
  record.write_second_level_cache
  record
end

#first(limit = nil) ⇒ Object

api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-first

Cacheable:

User.where(id: 1).first
User.where(id: 1).last

Uncacheable:

User.where(name: 'foo').first
User.where(age: 18).first


43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/second_level_cache/active_record/finder_methods.rb', line 43

def first(limit = nil)
  return super if limit.to_i > 1
  return super unless cachable?
  # only have primary_key condition in where
  if where_values_hash.length == 1 && where_values_hash.key?(primary_key)
    record = @klass.read_second_level_cache(where_values_hash[primary_key])
    return record if record
  end

  record = super
  record&.write_second_level_cache
  record
end