Chris@909: # Redmine - project management software Chris@909: # Copyright (C) 2006-2011 Jean-Philippe Lang Chris@909: # Chris@909: # This program is free software; you can redistribute it and/or Chris@909: # modify it under the terms of the GNU General Public License Chris@909: # as published by the Free Software Foundation; either version 2 Chris@909: # of the License, or (at your option) any later version. Chris@909: # Chris@909: # This program is distributed in the hope that it will be useful, Chris@909: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@909: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@909: # GNU General Public License for more details. Chris@909: # Chris@909: # You should have received a copy of the GNU General Public License Chris@909: # along with this program; if not, write to the Free Software Chris@909: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@909: Chris@909: class MemberRole < ActiveRecord::Base Chris@909: belongs_to :member Chris@909: belongs_to :role Chris@909: Chris@909: after_destroy :remove_member_if_empty Chris@909: Chris@909: after_create :add_role_to_group_users Chris@909: after_destroy :remove_role_from_group_users Chris@909: Chris@909: validates_presence_of :role Chris@909: Chris@909: def validate Chris@909: errors.add :role_id, :invalid if role && !role.member? Chris@909: end Chris@909: Chris@909: def inherited? Chris@909: !inherited_from.nil? Chris@909: end Chris@909: Chris@909: private Chris@909: Chris@909: def remove_member_if_empty Chris@909: if member.roles.empty? Chris@909: member.destroy Chris@909: end Chris@909: end Chris@909: Chris@909: def add_role_to_group_users Chris@909: if member.principal.is_a?(Group) Chris@909: member.principal.users.each do |user| Chris@909: user_member = Member.find_by_project_id_and_user_id(member.project_id, user.id) || Member.new(:project_id => member.project_id, :user_id => user.id) Chris@909: user_member.member_roles << MemberRole.new(:role => role, :inherited_from => id) Chris@909: user_member.save! Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: def remove_role_from_group_users Chris@909: MemberRole.find(:all, :conditions => { :inherited_from => id }).group_by(&:member).each do |member, member_roles| Chris@909: member_roles.each(&:destroy) Chris@909: if member && member.user Chris@909: Watcher.prune(:user => member.user, :project => member.project) Chris@909: end Chris@909: end Chris@909: end Chris@909: end