Module: Roleplayer::InstanceMethods
- Defined in:
- lib/roleplayer.rb
Instance Method Summary collapse
-
#add_roles(*args) ⇒ Object
Assigns a list of roles to the model instance.
-
#delete_roles(*args) ⇒ Object
Delete a list of assigned roles from a model instance.
-
#has_role?(role = nil) ⇒ Boolean
Returns true, if the model instance has
role
assigned to it. -
#reset_roles! ⇒ Object
Removes all roles from the model instance.
-
#role_symbols ⇒ Object
Compatibility method for
declarative_authorization
, which expect roles from a model instance as a list of symbols.
Instance Method Details
#add_roles(*args) ⇒ Object
Assigns a list of roles to the model instance. You can use any combination of arguments: they will be flattened and only previously existing roles will be added.
Examples
foo.add_roles( :admin ) #=> [ :admin ]
foo.add_roles( :admin, :editor ) #=> [ :admin, :editor ]
When the :invited
role doesn’t exist:
foo.add_roles( [:admin, :editor], [:invited, :vip] ) #=> [ :admin, :editor, :vip ]
102 103 104 105 |
# File 'lib/roleplayer.rb', line 102 def add_roles( *args ) args.flatten! args.each { |arg| roles.push( Role.find_by_name( arg.to_s ) ) if Role.valid?( arg ) } end |
#delete_roles(*args) ⇒ Object
Delete a list of assigned roles from a model instance. Same as add_roles
, arguments will be flattened before performing the delete, so you can pass multiple arguments at once for convenience.
Examples
foo.roles #=> [ :admin, :editor, :vip ]
foo.delete_roles( :admin ) #=> [ :editor, :vip ]
foo.delete_roles( [ :editor ], [ :vip, :invited ] ) #=> []
118 119 120 121 |
# File 'lib/roleplayer.rb', line 118 def delete_roles( *args ) args.flatten! args.each { |arg| roles.delete( Role.find_by_name( arg.to_s ) ) if has_role?( arg ) } end |
#has_role?(role = nil) ⇒ Boolean
Returns true, if the model instance has role
assigned to it.
Examples
foo.roles #=> [ :admin, :vip ]
foo.has_role? ( :admin ) #=> true
foo.has_role? ( "vip" ) #=> true
foo.has_role? ( :invited ) #=> false
84 85 86 87 |
# File 'lib/roleplayer.rb', line 84 def has_role?( role = nil ) return false if role.nil? roles.exists?( :name => role.to_s ) end |
#reset_roles! ⇒ Object
Removes all roles from the model instance.
Examples
foo.roles #=> [ :admin, :editor, :vip ]
foo.reset_roles!
foo.roles #=> []
132 133 134 |
# File 'lib/roleplayer.rb', line 132 def reset_roles! roles.clear end |
#role_symbols ⇒ Object
Compatibility method for declarative_authorization
, which expect roles from a model instance as a list of symbols.
70 71 72 |
# File 'lib/roleplayer.rb', line 70 def role_symbols roles.map { |r| r.name.to_sym } end |