Module: Royce::Methods
- Defined in:
- lib/royce/methods.rb
Class Method Summary collapse
-
.included(includer) ⇒ Object
Called when module included in a class includer == User includer.class == Class.
Instance Method Summary collapse
-
#add_role(name) ⇒ Object
These methods are included in all User instances.
- #allowed_role?(name) ⇒ Boolean
- #has_role?(name) ⇒ Boolean
- #remove_role(name) ⇒ Object
- #role_list ⇒ Object
Class Method Details
.included(includer) ⇒ Object
Called when module included in a class includer == User includer.class == Class
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/royce/methods.rb', line 7 def self.included includer # With instance eval, we can add instance methods # Add instance methods like user? admin? includer.instance_eval do # Loop through all available role names # and add a name? method that queries the has_role? method available_role_names.each do |name| define_method("#{name}?") do has_role? name end define_method("#{name}!") do add_role name end end end end |
Instance Method Details
#add_role(name) ⇒ Object
These methods are included in all User instances
30 31 32 33 34 35 36 |
# File 'lib/royce/methods.rb', line 30 def add_role name if allowed_role? name return if has_role? name role = Role.find_or_create_by(name: name.to_s) roles << role end end |
#allowed_role?(name) ⇒ Boolean
49 50 51 |
# File 'lib/royce/methods.rb', line 49 def allowed_role? name self.class.available_role_names.include? name.to_s end |
#has_role?(name) ⇒ Boolean
45 46 47 |
# File 'lib/royce/methods.rb', line 45 def has_role? name role_list.include? name.to_s end |
#remove_role(name) ⇒ Object
38 39 40 41 42 43 |
# File 'lib/royce/methods.rb', line 38 def remove_role name if allowed_role? name role = Role.find_by(name: name.to_s) roles.delete role end end |
#role_list ⇒ Object
53 54 55 |
# File 'lib/royce/methods.rb', line 53 def role_list roles.pluck(:name) end |