Permalink
Browse files

Moved watching methods to module Watchable

  • Loading branch information...
1 parent 0e40748 commit 10d850f258acf42ffecca23661977f2a8fc55ac3 @rondy committed Nov 28, 2011
Showing with 83 additions and 23 deletions.
  1. +0 −23 app/models/user.rb
  2. +23 −0 app/models/watchable.rb
  3. +5 −0 spec/factories.rb
  4. +55 −0 spec/models/watchable_user_spec.rb
View
@@ -9,27 +9,4 @@ class User < ActiveRecord::Base
has_many :watchings, :foreign_key => "watcher_id", :dependent => :destroy
has_many :watched_lists, :through => :watchings, :source => :watched_list
- # Watching methods may be violating SRP
- # TODO: move them to a new class (i.e Watchable), then User can be composed of that
-
- def watch!(todo_list)
- if can_watch? todo_list
- watchings.create! :watched_list => todo_list
- end
- end
-
- def can_watch?(todo_list)
- todo_list.public? && !todo_lists.include?(todo_list)
- end
-
- def unwatch!(todo_list)
- if watching? todo_list
- watched_lists.destroy todo_list
- end
- end
-
- def watching?(todo_list)
- !!watchings.find_by_watched_list_id todo_list
- end
-
end
View
@@ -0,0 +1,23 @@
+module Watchable
+
+ def watch!(todo_list)
+ if can_watch? todo_list
+ watchings.create! :watched_list => todo_list
+ end
+ end
+
+ def can_watch?(todo_list)
+ todo_list.public? && !todo_lists.include?(todo_list)
+ end
+
+ def unwatch!(todo_list)
+ if watching? todo_list
+ watched_lists.destroy todo_list
+ end
+ end
+
+ def watching?(todo_list)
+ !!watchings.find_by_watched_list_id(todo_list)
+ end
+
+end
View
@@ -11,4 +11,9 @@
password_confirmation "password"
end
+ factory :watching do
+ association :watcher, :factory => :user
+ association :watched_list, :factory => :todo_list
+ end
+
end
@@ -0,0 +1,55 @@
+require "spec_helper"
+
+describe Watchable do
+
+ let(:user) { Factory(:user) }
+
+ before do
+ user.extend Watchable
+ end
+
+ describe "watch a todo list" do
+
+ context "when todo list is public and user doesn't own todo list" do
+
+ let(:todo_list) { Factory(:todo_list, :private => false) }
+
+ it "can watch a todo list" do
+ user.can_watch?(todo_list).should be_true
+ end
+
+ it "can creates a watching relationship with todo list" do
+ lambda {
+ user.watch! todo_list
+ }.should change(user.watchings, :count).by(1)
+
+ user.watching?(todo_list).should be_true
+ end
+
+ end
+
+ end
+
+ describe "unwatch a todo list" do
+
+ context "when user is watching a todo list" do
+
+ let(:todo_list) { Factory(:todo_list, :private => false) }
+
+ before do
+ Factory.create(:watching, :watcher => user, :watched_list => todo_list)
+ end
+
+ it "can remove a watching relationship with todo list" do
+ lambda {
+ user.unwatch! todo_list
+ }.should change(user.watchings, :count).by(-1)
+
+ user.watching?(todo_list).should be_false
+ end
+
+ end
+
+ end
+
+end

0 comments on commit 10d850f

Please sign in to comment.