Skip to content

Instantly share code, notes, and snippets.

@jhoffner
Created May 27, 2014 23:17
Show Gist options
  • Save jhoffner/ddad1d3816ff2b725427 to your computer and use it in GitHub Desktop.
Save jhoffner/ddad1d3816ff2b725427 to your computer and use it in GitHub Desktop.
Batcan VS CanCan
# Batcan Style
class Project
# permission is enforced for all create/update/save calls. It is defined within the context of its own class and is only
# called when this particular permission is checked.
permission :save do |project, user|
next true if user.admin?
next true if project.owner == user
next true if project.collaborators.include?(user)
# at this point if we haven't returned true then we dont have permission. We are allowed to return a user readable
# string here (not sure if CanCan has this capability, I don't see it in the docs)
"Only admins, project owners and project collaborators can save this project"
end
# only enforced on create/update/save if due_date is modified
# NOTE: I don't believe CanCan has this capability, but I may be wrong
permission :save, :due_date do |project, user|
next true if user.admin? or project.owner == user
"Only admins and project owners can set the due date for this project"
end
end
# CanCan Style
class Project
end
# permissions for all objects are defined within one large initialize script within the ability class.
# Imagine if there were 50 permissions defined within the system. Note that the collaborators check here would make a database
# call. What if we don't need to check this permission? We end up making the call for no reason.
class Ability
include CanCan::Ability
def initialize(user)
alias_action :create, :update, :to => :save
can :save Project do |project|
user.admin? || project.owner == user || project.collaborators.include?(user)
end
end
end
### Usage:
project = Project.find('some-project')
## BatCan:
# can be called from anywhere in the code. Models, Specs, Rake Tasks... anywhere.
user.can? :save, project
## CanCan:
# can only be called from a controller.
can? :save, project
@danibrear
Copy link

I think there might be some confusion on the CanCan usage because it can actually be used in Views and Helpers as well: https://github.com/ryanb/cancan/wiki/Link-Helpers.
Also on a different model than the current_user as in your line 48 usage: https://github.com/ryanb/cancan/wiki/Ability-for-Other-Users

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment