Skip to content

Instantly share code, notes, and snippets.

@c0mrade
Forked from hrdwdmrbl/ability.rb
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save c0mrade/aa2b034666e1b334ae30 to your computer and use it in GitHub Desktop.

Select an option

Save c0mrade/aa2b034666e1b334ae30 to your computer and use it in GitHub Desktop.

Revisions

  1. Marc created this gist Jun 5, 2013.
    15 changes: 15 additions & 0 deletions ability.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    class Ability
    include CanCan::Ability

    def marshal_dump
    #blocks cannot be cached
    @rules.reject{|rule| rule.instance_variable_get :@block }.map{|rule| Marshal.dump(rule) }
    end
    def marshal_load array
    #blocks cannot be cached, so blocks must be re-defined
    can :read, Comment do |comment|
    comment.length > 100
    end
    @rules += array.map{|rule| Marshal.load(rule) }
    end
    end
    15 changes: 15 additions & 0 deletions application_controller.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    class ApplicationController < ActionController::Base
    if !Rails.env.development?
    def current_ability
    cached_ability = Rails.cache.read("#{current_user.cache_key}::ability")
    if cached_ability.present?
    ability = Marshal.load( cached_ability )
    ability.user = current_user
    else
    ability = super
    Rails.cache.write("#{current_user.cache_key}::ability", Marshal.dump( ability ))
    end
    @current_ability = ability
    end
    end
    end