OSDN Git Service

Move database.yml to template
[redminele/redminele.git] / redmine / vendor / plugins / acts_as_watchable / lib / acts_as_watchable.rb
1 # ActsAsWatchable
2 module Redmine
3   module Acts
4     module Watchable
5       def self.included(base) 
6         base.extend ClassMethods
7       end 
8
9       module ClassMethods
10         def acts_as_watchable(options = {})
11           return if self.included_modules.include?(Redmine::Acts::Watchable::InstanceMethods)          
12           send :include, Redmine::Acts::Watchable::InstanceMethods
13           
14           class_eval do
15             has_many :watchers, :as => :watchable, :dependent => :delete_all
16             has_many :watcher_users, :through => :watchers, :source => :user
17             
18             attr_protected :watcher_ids, :watcher_user_ids
19           end
20         end
21       end
22
23       module InstanceMethods
24         def self.included(base)
25           base.extend ClassMethods
26         end
27         
28         # Returns an array of users that are proposed as watchers
29         def addable_watcher_users
30           self.project.users.sort - self.watcher_users
31         end
32         
33         # Adds user as a watcher
34         def add_watcher(user)
35           self.watchers << Watcher.new(:user => user)
36         end
37         
38         # Removes user from the watchers list
39         def remove_watcher(user)
40           return nil unless user && user.is_a?(User)
41           Watcher.delete_all "watchable_type = '#{self.class}' AND watchable_id = #{self.id} AND user_id = #{user.id}"
42         end
43         
44         # Adds/removes watcher
45         def set_watcher(user, watching=true)
46           watching ? add_watcher(user) : remove_watcher(user)
47         end
48         
49         # Returns true if object is watched by user
50         def watched_by?(user)
51           !!(user && self.watchers.detect {|w| w.user_id == user.id })
52         end
53         
54         # Returns an array of watchers' email addresses
55         def watcher_recipients
56           notified = watchers.collect(&:user).select(&:active?)
57           if respond_to?(:visible?)
58             notified.reject! {|user| !visible?(user)}
59           end
60           notified.collect(&:mail).compact
61         end
62
63         module ClassMethods
64           # Returns the objects that are watched by user
65           def watched_by(user)
66             find(:all, 
67                  :include => :watchers,
68                  :conditions => ["#{Watcher.table_name}.user_id = ?", user.id])
69           end
70         end
71       end
72     end
73   end
74 end