使用 simple_cacheable 做缓存

第一步,定义要缓存的东东

include Cacheable

然后就有5个方法

association_cache

attribute_cache

class_method_cache

key_cache

method_cache

类似

  model_cache do
    with_key                          # User.find_cached(1)
    with_attribute :login             # User.find_cached_by_login('flyerhzm')
    with_method :last_post            # user.cached_last_post
    with_association :posts, :account # user.cached_posts, user.cached_account
    with_class_method  :default_post        # Post.default_post
  end

第二步,改变调用方法

会把原有的调用方法改为 cached_前缀 或者 _cached后缀

第三步,有缓存就有释放缓存

它们统一用 expire_model_cache

def expire_model_cache
  expire_key_cache            if self.class.cached_key                    
  expire_attribute_cache      if self.class.cached_indices.present?       
  expire_all_attribute_cache  if self.class.cached_indices.present?
  expire_method_cache         if self.class.cached_methods.present?       
  expire_class_method_cache   if self.class.cached_class_methods.present?

  if self.class.cached_associations.present?                              
    self.class.cached_associations.each do |assoc|                        
      expire_association_cache(assoc)                                     
    end 
  end
end


你可能感兴趣的:(使用 simple_cacheable 做缓存)