-->

Can Can selectively cache abilities

2019-09-02 09:52发布

问题:

I know about caching the whole current_ability.

Something like

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

But is there is a way to cache a single ability ? for example I do this :

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

回答1:

I did this to cache the whole current_ability object

In ApplicationController

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