From c611bd07f572a8689af13135772ade863742914e Mon Sep 17 00:00:00 2001 From: Antonio Terceiro Date: Fri, 17 Aug 2012 14:47:06 -0300 Subject: [PATCH] Move comment notification into a background job --- app/models/comment.rb | 7 ++++++- app/models/comment_handler.rb | 10 ++++++++++ test/unit/comment_handler_test.rb | 24 ++++++++++++++++++++++++ test/unit/comment_notifier_test.rb | 1 + 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 app/models/comment_handler.rb create mode 100644 test/unit/comment_handler_test.rb diff --git a/app/models/comment.rb b/app/models/comment.rb index ac9a084..0939a20 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -85,7 +85,12 @@ class Comment < ActiveRecord::Base end end - after_create :notify_by_mail + after_create :schedule_notification + + def schedule_notification + Delayed::Job.enqueue CommentHandler.new(self.id) + end + def notify_by_mail if source.kind_of?(Article) && article.notify_comments? if !article.profile.notification_emails.empty? diff --git a/app/models/comment_handler.rb b/app/models/comment_handler.rb new file mode 100644 index 0000000..577ea1d --- /dev/null +++ b/app/models/comment_handler.rb @@ -0,0 +1,10 @@ +class CommentHandler < Struct.new(:comment_id) + + def perform + comment = Comment.find(comment_id) + comment.notify_by_mail + rescue ActiveRecord::RecordNotFound + # just ignore non-existing comments + end + +end diff --git a/test/unit/comment_handler_test.rb b/test/unit/comment_handler_test.rb new file mode 100644 index 0000000..3b4dbc8 --- /dev/null +++ b/test/unit/comment_handler_test.rb @@ -0,0 +1,24 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class CommentHandlerTest < ActiveSupport::TestCase + + should 'receive comment id' do + handler = CommentHandler.new(99) + assert_equal 99, handler.comment_id + end + + should 'not crash with unexisting comment' do + handler = CommentHandler.new(-1) + handler.perform + end + + should 'call Comment#notify_by_mail' do + handler = CommentHandler.new(-1) + comment = Comment.new + Comment.stubs(:find).with(-1).returns(comment) + comment.expects(:notify_by_mail) + + handler.perform + end + +end diff --git a/test/unit/comment_notifier_test.rb b/test/unit/comment_notifier_test.rb index 5d318fa..71dfd0e 100644 --- a/test/unit/comment_notifier_test.rb +++ b/test/unit/comment_notifier_test.rb @@ -84,6 +84,7 @@ class CommentNotifierTest < ActiveSupport::TestCase def create_comment_and_notify(args) Comment.create!(args) + process_delayed_job_queue end def read_fixture(action) -- libgit2 0.21.2