I want to optimize my code How can i ?
If I added new role then one more condition add but that i don’t want. I want any no. of roles but i need only one conditions is it possible?
after_save :announcement_send
def announcement_send
if self.send_now == true && self.group_id.to_s == "Artists"
User.having_role("artist").each do |user|
ArtistMailer.announcement_user(self, user).deliver
end
elsif self.send_now == true && self.group_id.to_s == "Fans"
User.having_role("fan").each do |user|
ArtistMailer.announcement_user(self, user).deliver
end
elsif self.send_now == true && self.group_id.to_s == "Both"
User.not_having_role("admin").each do |user|
ArtistMailer.announcement_user(self, user).deliver
end
end
end
Not really tested this out but I would break this down like this:
This code assumes the group_id always comes along as the plural form of the role the users are in. So Artists means the “artist” role.
Of course this assumes all roles are valid group_ids. If that’s not the case you can check the group_id against a whitelist of possible values inside
def role: