Module: Canard::UserModel

Defined in:
lib/canard/user_model.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_user(*args) ⇒ Object

Canard applies roles to a model using the acts_as_user class method. The following User model will be given the :manager and :admin roles

class User < ActiveRecord::Base

  acts_as_user :roles =>  :manager, :admin

end

If using Canard with a non ActiveRecord class you can still assign roles but you will need to extend the class with Canard::UserModel and add a roles_mask attribute.

class User

  extend Canard::UserModel

  attr_accessor :roles_mask

  acts_as_user :roles =>  :manager, :admin

end

Scopes

Beyond applying the roles to model acts_as_user also creates some useful scopes on the User model for ActiveRecord models;

User.with_any_role(:manager, :admin)

returns all the managers and admins

User.with_all_roles(:manager, :admin)

returns only the users with both the manager and admin roles

User.admins

returns all the admins as

User.managers

returns all the users with the maager role likewise

User.non_admins

returns all the users who don’t have the admin role and

User.non_managers

returns all the users who don’t have the manager role.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/canard/user_model.rb', line 55

def acts_as_user(*args)
  include RoleModel

  options = args.extract_options!.symbolize_keys

  roles options[:roles] if options.has_key?(:roles) && has_roles_mask_attribute? || has_roles_mask_accessors?

  if respond_to?(:table_exists?) && table_exists?
    valid_roles.each do |role|
      define_scopes_for_role role
    end

    define_scope_method(:with_any_role) do |*roles|
      where("#{role_mask_column} & :role_mask > 0", { :role_mask => mask_for(*roles) })
    end

    define_scope_method(:with_all_roles) do |*roles|
      where("#{role_mask_column} & :role_mask = :role_mask", { :role_mask => mask_for(*roles) })
    end
  end
end