summaryrefslogtreecommitdiffstats
path: root/vendor/plugins/acts_as_watchable/lib/acts_as_watchable.rb
blob: c13da4fd4665e15e81cee8bfafffe0136fca6096 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# ActsAsWatchable
module Redmine
  module Acts
    module Watchable
      def self.included(base) 
        base.extend ClassMethods
      end 

      module ClassMethods
        def acts_as_watchable(options = {})
          return if self.included_modules.include?(Redmine::Acts::Watchable::InstanceMethods)          
          send :include, Redmine::Acts::Watchable::InstanceMethods
          
          class_eval do
            has_many :watchers, :as => :watchable, :dependent => :delete_all
            has_many :watcher_users, :through => :watchers, :source => :user
            
            attr_protected :watcher_ids, :watcher_user_ids
          end
        end
      end

      module InstanceMethods
        def self.included(base)
          base.extend ClassMethods
        end
        
        # Returns an array of users that are proposed as watchers
        def addable_watcher_users
          self.project.users.sort - self.watcher_users
        end
        
        # Adds user as a watcher
        def add_watcher(user)
          self.watchers << Watcher.new(:user => user)
        end
        
        # Removes user from the watchers list
        def remove_watcher(user)
          return nil unless user && user.is_a?(User)
          Watcher.delete_all "watchable_type = '#{self.class}' AND watchable_id = #{self.id} AND user_id = #{user.id}"
        end
        
        # Adds/removes watcher
        def set_watcher(user, watching=true)
          watching ? add_watcher(user) : remove_watcher(user)
        end
        
        # Returns true if object is watched by user
        def watched_by?(user)
          !!(user && self.watchers.detect {|w| w.user_id == user.id })
        end
        
        # Returns an array of watchers' email addresses
        def watcher_recipients
          notified = watchers.collect(&:user).select(&:active?)
          if respond_to?(:visible?)
            notified.reject! {|user| !visible?(user)}
          end
          notified.collect(&:mail).compact
        end

        module ClassMethods
          # Returns the objects that are watched by user
          def watched_by(user)
            find(:all, 
                 :include => :watchers,
                 :conditions => ["#{Watcher.table_name}.user_id = ?", user.id])
          end
        end
      end
    end
  end
end