Module: TinyCache::ActiveRecord::Base::ClassMethods

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#tiny_cache_optionsObject (readonly)

Returns the value of attribute tiny_cache_options.



20
21
22
# File 'lib/tiny_cache/active_record/base.rb', line 20

def tiny_cache_options
  @tiny_cache_options
end

Instance Method Details

#acts_as_tiny_cached(*args) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tiny_cache/active_record/base.rb', line 22

def acts_as_tiny_cached(*args)
  options = args.extract_options!

  @tiny_cache_enabled = true
  @tiny_cache_options = options
  @tiny_cache_options[:expires_in] ||= 1.week
  @tiny_cache_options[:version] ||= 0

  after_commit :expire_tiny_cache, :on => :destroy
  after_commit :update_tiny_cache, :on => :update
  after_commit :write_tiny_cache,  :on => :create
end

#cache_storeObject



55
56
57
# File 'lib/tiny_cache/active_record/base.rb', line 55

def cache_store
  ::TinyCache::Config.cache_store
end

#expire_tiny_cache(id) ⇒ Object



79
80
81
# File 'lib/tiny_cache/active_record/base.rb', line 79

def expire_tiny_cache(id)
  TinyCache.cache_store.delete(tiny_cache_key(id)) if self.tiny_cache_enabled?
end

#loggerObject



59
60
61
# File 'lib/tiny_cache/active_record/base.rb', line 59

def logger
  ::TinyCache::Config.logger
end

#read_tiny_cache(id) ⇒ Object



75
76
77
# File 'lib/tiny_cache/active_record/base.rb', line 75

def read_tiny_cache(id)
  RecordMarshal.load(TinyCache.cache_store.read(tiny_cache_key(id))) if self.tiny_cache_enabled?
end

#tiny_cache_enabled?Boolean

是否启用cache

Returns:

  • (Boolean)


42
43
44
# File 'lib/tiny_cache/active_record/base.rb', line 42

def tiny_cache_enabled?
  !!@tiny_cache_enabled
end

#tiny_cache_key(id) ⇒ Object



71
72
73
# File 'lib/tiny_cache/active_record/base.rb', line 71

def tiny_cache_key(id)
  "#{tiny_cache_key_prefix}/models/#{self.name}/#{id}/#{tiny_cache_version}"
end

#tiny_cache_key_prefixObject



63
64
65
# File 'lib/tiny_cache/active_record/base.rb', line 63

def tiny_cache_key_prefix
  ::TinyCache::Config.cache_key_prefix
end

#tiny_cache_versionObject



67
68
69
# File 'lib/tiny_cache/active_record/base.rb', line 67

def tiny_cache_version
  tiny_cache_options[:version]
end

#update_counters_with_tiny_cache(id, counters) ⇒ Object



35
36
37
38
39
# File 'lib/tiny_cache/active_record/base.rb', line 35

def update_counters_with_tiny_cache(id, counters)
  update_counters_without_tiny_cache(id, counters).tap do
    Array(id).each{|i| expire_tiny_cache(i)}
  end
end

#without_tiny_cacheObject

不启用cache



47
48
49
50
51
52
53
# File 'lib/tiny_cache/active_record/base.rb', line 47

def without_tiny_cache
  old, @tiny_cache_enabled = @tiny_cache_enabled, false

  yield if block_given?
ensure
  @tiny_cache_enabled = old
end