Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@avakhov
Created August 27, 2011 19:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avakhov/1175760 to your computer and use it in GitHub Desktop.
Save avakhov/1175760 to your computer and use it in GitHub Desktop.
six gem usage
class AbilityRules
class AccessDenied < Exception
end
def self.allowed(user, subject)
rules = []
railse [user, subject].inspect # <--- this exception was rescued by six rescue block (of course it need only in development for debug :)
return rules unless user
rules << :manage if subject == User and user.perm_users_manage?
rules << :show if subject == Version and user.perm_versions_show?
# ...
rules
end
end
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :create_ability
helper_method :can?
helper_method :should!
rescue_from AbilityRules::AccessDenied do |exception|
redirect_to root_url, :alert => 'Access denied.'
end
protected
def create_ability
@ability = Six.new
@ability.add(:ability, AbilityRules)
end
def can?(action, subject)
@ability.allowed?(current_user, action, subject)
end
def should!(action, subject)
raise AbilityRules::AccessDenied unless can?(action, subject)
end
end
module ApplicationHelper
def render_menu
content_tag(:div, :class => 'menu') do
out = []
out << link_to_unless_current('users', users_path) if can? :manage, User
out << link_to_unless_current('versions', versions_index_path) if can? :show, Version
# ...
out.join(" ").html_safe
end
end
end
class UsersController < ApplicationController
before_filter :authenticate_user!
before_filter :check_ability, :except => [:profile, :update_profile]
# ...
private
def check_ability
should!(:manage, User)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment