Permalink
Browse files

adding caching to current_ability class method, if you're overriding …

…this be sure to add caching there too
  • Loading branch information...
1 parent 37f482e commit ef5900c5b1a2ea8882aaa1c8fb25af00033cbc7e @ryanb committed Apr 16, 2010
Showing with 16 additions and 14 deletions.
  1. +2 −0 CHANGELOG.rdoc
  2. +4 −3 README.rdoc
  3. +10 −11 lib/cancan/controller_additions.rb
View
@@ -1,5 +1,7 @@
1.1.0 (not released)
+* Adding caching to current_ability controller method, if you're overriding this be sure to add caching too.
+
* Adding "can" method to Active Record for fetching records matching a specific ability
* Adding conditions behavior to Ability#can and fetch with Ability#conditions - see issue #53
View
@@ -202,9 +202,10 @@ CanCan makes two assumptions about your application.
You can override these by overriding the "current_ability" method in your ApplicationController.
- def current_ability
- UserAbility.new(current_account) # instead of Ability.new(current_user)
- end
+ def current_ability
+ # instead of Ability.new(current_user)
+ @current_ability ||= UserAbility.new(current_account)
+ end
That's it!
@@ -142,20 +142,19 @@ def unauthorized!(message = "You are not authorized to access this page.")
raise AccessDenied, message
end
- # Creates and returns the current user's ability. You generally do not invoke
- # this method directly, instead you can override this method to change its
- # behavior if the Ability class or current_user method are different.
+ # Creates and returns the current user's ability and caches it. If you
+ # want to override how the Ability is defined then this is the place.
+ # Just define the method in the controller to change behavior.
#
# def current_ability
- # UserAbility.new(current_account) # instead of Ability.new(current_user)
+ # # instead of Ability.new(current_user)
+ # @current_ability ||= UserAbility.new(current_account)
# end
#
+ # Notice it is important to cache the ability object so it is not
+ # recreated every time.
def current_ability
- ::Ability.new(current_user)
- end
-
- def cached_current_ability
- @current_ability ||= current_ability
+ @current_ability ||= ::Ability.new(current_user)
end
# Use in the controller or view to check the user's permission for a given action
@@ -171,15 +170,15 @@ def cached_current_ability
#
# This simply calls "can?" on the current_ability. See Ability#can?.
def can?(*args)
- cached_current_ability.can?(*args)
+ current_ability.can?(*args)
end
# Convenience method which works the same as "can?" but returns the opposite value.
#
# cannot? :destroy, @project
#
def cannot?(*args)
- cached_current_ability.cannot?(*args)
+ current_ability.cannot?(*args)
end
end
end

0 comments on commit ef5900c

Please sign in to comment.