可以有选择地缓存能力

时间:2013-09-17 12:09:19

标签: caching ruby-on-rails-3.2 cancan ruby-2.0

我知道缓存整个current_ability

这样的东西
def current_ability
  cached_ability = Rails.cache.read("#{current_user.cache_key}::ability")
  if cached_ability.present?
    ability = Marshal.load( cached_ability )
  else
    ability = super
    Rails.cache.write("#{current_user.cache_key}::ability", Marshal.dump( ability ))
  end
  @current_ability = ability
end

但是有没有办法缓存单一能力? 例如,我这样做:

Rails.cache.fetch("#{user.cache_key}::comments::ability") do
  can :manage, Comment, :article_id => articles_ids
end

1 个答案:

答案 0 :(得分:4)

我这样做是为了缓存整个current_ability对象

ApplicationController

def current_ability
  @current_ability = Rails.cache.fetch("#{current_user.cache_key}::ability") do
    super
  end
end unless Rails.env.development?