pluginaweek / has_roles

Demonstrates a reference implementation for handling role management

has_roles / lib / has_roles.rb
100644 39 lines (34 sloc) 1.316 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'has_roles/authorization_helper'
require 'has_roles/url_helper'
 
# Adds a generic implementation for dealing with role management
module HasRoles
  module MacroMethods
    # Indicates that the model has roles. This will create the following
    # associations:
    # * +role_assignments+ - The join association for roles that have been
    # assigned to a record in this model
    # * +roles+ - The actual roles through the join association
    def has_roles
      has_many :role_assignments, :class_name => 'RoleAssignment', :as => :assignee, :dependent => :destroy
      has_many :roles, :through => :role_assignments
      
      include HasRoles::InstanceMethods
    end
  end
  
  module InstanceMethods
    # Checks whether this user is authorized to access the given url.
    #
    # == Examples
    #
    # user = User.find(1)
    # user.authorized_for?(:controller => 'admin/messages')
    # user.authorized_for?(:controller => 'admin/messages', :action => 'destroy')
    # user.authorized_for?('admin/messages')
    # user.authorized_for?('http://localhost:3000/admin/messages')
    def authorized_for?(options = '')
      !Permission.restricts?(options) || roles.authorized_for(options).exists?
    end
  end
end
 
ActiveRecord::Base.class_eval do
  extend HasRoles::MacroMethods
end