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

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

Instance Method Summary collapse

Instance Method Details

#acts_as_tiny_cached(*args) ⇒ Object



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

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

  @tiny_cache_enabled = true

  if options.key?(:expires_in)
    self.tiny_cache_options[:expires_in] = options[:expires_in]
  end

  if options.key?(:version)
    self.tiny_cache_options[:version] = options[:version]
  end

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

#cache_storeObject



65
66
67
# File 'lib/tiny_cache/active_record/base.rb', line 65

def cache_store
  ::TinyCache::Config.cache_store
end

#expire_tiny_cache(id) ⇒ Object



89
90
91
# File 'lib/tiny_cache/active_record/base.rb', line 89

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

#loggerObject



69
70
71
# File 'lib/tiny_cache/active_record/base.rb', line 69

def logger
  ::TinyCache::Config.logger
end

#read_tiny_cache(id) ⇒ Object



85
86
87
# File 'lib/tiny_cache/active_record/base.rb', line 85

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)


52
53
54
# File 'lib/tiny_cache/active_record/base.rb', line 52

def tiny_cache_enabled?
  !!@tiny_cache_enabled
end

#tiny_cache_key(id) ⇒ Object



81
82
83
# File 'lib/tiny_cache/active_record/base.rb', line 81

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

#tiny_cache_key_prefixObject



73
74
75
# File 'lib/tiny_cache/active_record/base.rb', line 73

def tiny_cache_key_prefix
  ::TinyCache::Config.cache_key_prefix
end

#tiny_cache_optionsObject



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

def tiny_cache_options
  @tiny_cache_options ||= {
    :expires_in => 1.week,
    :version    => 0
  }
end

#tiny_cache_versionObject



77
78
79
# File 'lib/tiny_cache/active_record/base.rb', line 77

def tiny_cache_version
  tiny_cache_options ? tiny_cache_options[:version] : ''
end

#update_counters_with_tiny_cache(id, counters) ⇒ Object



45
46
47
48
49
# File 'lib/tiny_cache/active_record/base.rb', line 45

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



57
58
59
60
61
62
63
# File 'lib/tiny_cache/active_record/base.rb', line 57

def without_tiny_cache
  old, @tiny_cache_enabled = @tiny_cache_enabled, false

  yield if block_given?
ensure
  @tiny_cache_enabled = old
end