Created
August 27, 2011 19:18
-
-
Save avakhov/1175760 to your computer and use it in GitHub Desktop.
six gem usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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