Conditions | 3 |
Total Lines | 55 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | # frozen_string_literal: true |
||
49 | def update_roles(roles) |
||
50 | # Check that the user can manage users |
||
51 | return true unless current_user.highest_priority_role.get_permission("can_manage_users") |
||
52 | |||
53 | new_roles = roles.split(' ').map(&:to_i) |
||
54 | old_roles = @user.roles.pluck(:id) |
||
55 | |||
56 | added_role_ids = new_roles - old_roles |
||
57 | removed_role_ids = old_roles - new_roles |
||
58 | |||
59 | added_roles = [] |
||
60 | removed_roles = [] |
||
61 | current_user_role = current_user.highest_priority_role |
||
62 | |||
63 | # Check that the user has the permissions to add all the new roles |
||
64 | added_role_ids.each do |id| |
||
65 | role = Role.find(id) |
||
66 | |||
67 | # Admins are able to add the admin role to other users. All other roles may only |
||
68 | # add roles with a higher priority |
||
69 | if (role.priority > current_user_role.priority || current_user_role.name == "admin") && |
||
70 | role.provider == @user_domain |
||
71 | added_roles << role |
||
72 | else |
||
73 | return false |
||
74 | end |
||
75 | end |
||
76 | |||
77 | # Check that the user has the permissions to remove all the deleted roles |
||
78 | removed_role_ids.each do |id| |
||
79 | role = Role.find(id) |
||
80 | |||
81 | # Admins are able to remove the admin role from other users. All other roles may only |
||
82 | # remove roles with a higher priority |
||
83 | if (role.priority > current_user_role.priority || current_user_role.name == "admin") && |
||
84 | role.provider == @user_domain |
||
85 | removed_roles << role |
||
86 | else |
||
87 | return false |
||
88 | end |
||
89 | end |
||
90 | |||
91 | # Send promoted/demoted emails |
||
92 | added_roles.each { |role| send_user_promoted_email(@user, role) if role.get_permission("send_promoted_email") } |
||
93 | removed_roles.each { |role| send_user_demoted_email(@user, role) if role.get_permission("send_demoted_email") } |
||
94 | |||
95 | # Update the roles |
||
96 | @user.roles.delete(removed_roles) |
||
97 | @user.roles << added_roles |
||
98 | |||
99 | # Make sure each user always has at least the user role |
||
100 | @user.roles = [Role.find_by(name: "user", provider: @user_domain)] if @user.roles.count.zero? |
||
101 | |||
102 | @user.save! |
||
103 | end |
||
104 | |||
173 |