Chris@909: # ActsAsWatchable Chris@909: module Redmine Chris@909: module Acts Chris@909: module Watchable Chris@909: def self.included(base) Chris@909: base.extend ClassMethods Chris@909: end Chris@909: Chris@909: module ClassMethods Chris@909: def acts_as_watchable(options = {}) Chris@909: return if self.included_modules.include?(Redmine::Acts::Watchable::InstanceMethods) Chris@909: send :include, Redmine::Acts::Watchable::InstanceMethods Chris@909: Chris@909: class_eval do Chris@909: has_many :watchers, :as => :watchable, :dependent => :delete_all Chris@909: has_many :watcher_users, :through => :watchers, :source => :user, :validate => false Chris@909: Chris@909: named_scope :watched_by, lambda { |user_id| Chris@909: { :include => :watchers, Chris@909: :conditions => ["#{Watcher.table_name}.user_id = ?", user_id] } Chris@909: } Chris@909: attr_protected :watcher_ids, :watcher_user_ids Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: module InstanceMethods Chris@909: def self.included(base) Chris@909: base.extend ClassMethods Chris@909: end Chris@909: Chris@909: # Returns an array of users that are proposed as watchers Chris@909: def addable_watcher_users Chris@909: users = self.project.users.sort - self.watcher_users Chris@909: if respond_to?(:visible?) Chris@909: users.reject! {|user| !visible?(user)} Chris@909: end Chris@909: users Chris@909: end Chris@909: Chris@909: # Adds user as a watcher Chris@909: def add_watcher(user) Chris@909: self.watchers << Watcher.new(:user => user) Chris@909: end Chris@909: Chris@909: # Removes user from the watchers list Chris@909: def remove_watcher(user) Chris@909: return nil unless user && user.is_a?(User) Chris@909: Watcher.delete_all "watchable_type = '#{self.class}' AND watchable_id = #{self.id} AND user_id = #{user.id}" Chris@909: end Chris@909: Chris@909: # Adds/removes watcher Chris@909: def set_watcher(user, watching=true) Chris@909: watching ? add_watcher(user) : remove_watcher(user) Chris@909: end Chris@909: Chris@909: # Returns true if object is watched by +user+ Chris@909: def watched_by?(user) Chris@909: !!(user && self.watcher_user_ids.detect {|uid| uid == user.id }) Chris@909: end Chris@909: Chris@909: # Returns an array of watchers' email addresses Chris@909: def watcher_recipients Chris@909: notified = watcher_users.active Chris@909: notified.reject! {|user| user.mail_notification == 'none'} Chris@909: Chris@909: if respond_to?(:visible?) Chris@909: notified.reject! {|user| !visible?(user)} Chris@909: end Chris@909: notified.collect(&:mail).compact Chris@909: end Chris@909: Chris@909: module ClassMethods; end Chris@909: end Chris@909: end Chris@909: end Chris@909: end