Skip to content

Instantly share code, notes, and snippets.

@pirj
Created July 17, 2011 20:23
Show Gist options
  • Save pirj/1088021 to your computer and use it in GitHub Desktop.
Save pirj/1088021 to your computer and use it in GitHub Desktop.
Padrino and CanCan
# include this in app file
# this is for Role Based Access Controle, can be much shorter
class Ability
include CanCan::Ability
def initialize account
@abilities ||= {}
allow [:any, :manager, :manufacturer, :admin] do
can :base, :index
can :products, :index
can :manufacturers, :index
can :manufacturers, :find
can :manufacturers, :search
end
allow :manager do
end
allow :admin do
can :manufacturers, :new
can :manufacturers, :destroy
can :accounts, :index
end
role = account.role.to_sym rescue :any
(@abilities[role] || []).each do |block|
block.call
end
end
def allow roles, &block
if roles.is_a? Array
roles.each do |role| allow_role role, &block end
else
allow_role roles, &block
end
end
def allow_role role, &block
@abilities[role] ||= []
@abilities[role] << block
end
end
App.controllers :manufacturers do
include CanCan::ControllerAdditions
get :index do
authorize! :manufacturers, :index
manufacturers = Manufacturer.page params[:page]
render 'manufacturers/index', :locals => {:manufacturers => manufacturers}
end
...
end
-if can? :manufacturers, :index
%li=link_to pt(:list), :manufacturers, :index
-if can? :manufacturers, :find
%li=safe_link_to pt(:find), :manufacturers, :find
-if can? :manufacturers, :new
%li=safe_link_to pt(:new), :manufacturers, :new
# include this in app file
module CanCan
module ControllerAdditions
def current_user
current_account
end
def self.included(base)
base.extend ClassMethods
# base.helper_method :can?, :cannot?, :current_ability
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment