]> source.dussan.org Git - redmine.git/commitdiff
Adds Watcher.any_watched? to check if at least one object of a collection is watched.
authorJean-Philippe Lang <jp_lang@yahoo.fr>
Tue, 11 Jun 2013 18:25:05 +0000 (18:25 +0000)
committerJean-Philippe Lang <jp_lang@yahoo.fr>
Tue, 11 Jun 2013 18:25:05 +0000 (18:25 +0000)
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@11959 e93f8b46-1217-0410-a6f0-8f06a7374b81

app/helpers/watchers_helper.rb
app/models/watcher.rb
test/unit/watcher_test.rb

index b69837c2a3f28629508536f6b8e1a7dd603d1072..0d3951203816edef1559195836d780d31d0ca169 100644 (file)
@@ -28,7 +28,7 @@ module WatchersHelper
     return '' unless user && user.logged?
     objects = Array.wrap(objects)
 
-    watched = objects.any? {|object| object.watched_by?(user)}
+    watched = Watcher.any_watched?(objects, user)
     css = [watcher_css(objects), watched ? 'icon icon-fav' : 'icon icon-fav-off'].join(' ')
     text = watched ? l(:button_unwatch) : l(:button_watch)
     url = watch_path(
index 1cea711b779727a0c1ef542cbfe3284c34ce34c1..3a37aa3238620bf699a123cb445c2eaab4490f5f 100644 (file)
@@ -23,6 +23,19 @@ class Watcher < ActiveRecord::Base
   validates_uniqueness_of :user_id, :scope => [:watchable_type, :watchable_id]
   validate :validate_user
 
+  # Returns true if at least one object among objects is watched by user
+  def self.any_watched?(objects, user)
+    objects = objects.reject(&:new_record?)
+    if objects.any?
+      objects.group_by {|object| object.class.base_class}.each do |base_class, objects|
+        if Watcher.where(:watchable_type => base_class.name, :watchable_id => objects.map(&:id), :user_id => user.id).exists?
+          return true
+        end
+      end
+    end
+    false
+  end
+
   # Unwatch things that users are no longer allowed to view
   def self.prune(options={})
     if options.has_key?(:user)
index 6719ee8a625c9e29bffe51d37ab4dcc7a7c0f9be..fb1163aaefe6e248d204480ecf4ebe1e52efd619 100644 (file)
@@ -99,6 +99,23 @@ class WatcherTest < ActiveSupport::TestCase
     assert_nil issue.addable_watcher_users.detect {|user| !issue.visible?(user)}
   end
 
+  def test_any_watched_should_return_false_if_no_object_is_watched
+    objects = (0..2).map {Issue.generate!}
+
+    assert_equal false, Watcher.any_watched?(objects, @user)
+  end
+
+  def test_any_watched_should_return_true_if_one_object_is_watched
+    objects = (0..2).map {Issue.generate!}
+    objects.last.add_watcher(@user)
+
+    assert_equal true, Watcher.any_watched?(objects, @user)
+  end
+
+  def test_any_watched_should_return_false_with_no_object
+    assert_equal false, Watcher.any_watched?([], @user)
+  end
+
   def test_recipients
     @issue.watchers.delete_all
     @issue.reload