Module: TinyCache::ActiveRecord::FetchByUniqKey

Defined in:
lib/tiny_cache/active_record/fetch_by_uniq_key.rb

Instance Method Summary collapse

Instance Method Details

#tiny_cache_find_by(conditions = {}) ⇒ Object

用来根据属性进行查询缓存, 一般适合是唯一不变的条件 eg:

1. topic.tiny_cache_find_by :uid => 1, :category_id => 2


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tiny_cache/active_record/fetch_by_uniq_key.rb', line 25

def tiny_cache_find_by conditions={}
  uniq_cache_key = tiny_cache_uniq_key(conditions)

  # 根据cache_key获取id
  if iid = TinyCache.cache_store.read(uniq_cache_key)
    begin
      self.find iid
    ensure ::ActiveRecord::RecordNotFound
      nil
    end
  else
    record = self.where(conditions).first
    record.tap do |record|
      TinyCache.cache_store.write(uniq_cache_key, record.id)
    end if record
  end
end

#tiny_cache_find_by!(conditions = {}) ⇒ Object



43
44
45
# File 'lib/tiny_cache/active_record/fetch_by_uniq_key.rb', line 43

def tiny_cache_find_by! conditions={}
  tiny_cache_find_by(conditions) || raise(::ActiveRecord::RecordNotFound)
end

#tiny_cache_find_by_id(id) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/tiny_cache/active_record/fetch_by_uniq_key.rb', line 5

def tiny_cache_find_by_id id
  begin
    record = read_tiny_cache(id)
    record = self.find_by_id(id) if record.nil?
    record.write_tiny_cache if record
    record
  ensure ::ActiveRecord::RecordNotFound
    nil
  end
end

#tiny_cache_find_by_id!(id) ⇒ Object



16
17
18
# File 'lib/tiny_cache/active_record/fetch_by_uniq_key.rb', line 16

def tiny_cache_find_by_id! id
  tiny_cache_find_by_id(id) || raise(::ActiveRecord::RecordNotFound)
end