27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

gem 'delayed_job'<br />

Background workers<br />

Then you’ll need to run bundle install to install it. Once you’re done there, you can<br />

run this command, which will generate a migration to create the delayed_job table:<br />

rails g delayed_job<br />

You can now run this migration with rake db:migrate db:test:prepare. That’s all<br />

that’s needed to set up the gem itself.<br />

Your next task is to create a job. A job is any object that responds to perform. This<br />

method needs to perform the action of sending out the email to all the watchers of<br />

the ticket, which is currently the responsibility of the after_create method in<br />

CommentObserver, which uses this code:<br />

watchers = comment.ticket.watchers - [comment.user]<br />

watchers.each do |user|<br />

Notifier.comment_updated(comment, user).deliver<br />

end<br />

You’ll take this code out of the after_create method and replace it with code to<br />

enqueue your job to be performed, using a method given to you by the delayed_job<br />

gem:<br />

Delayed::Job.enqueue CommentNotifierJob.new(comment.id)<br />

The CommentNotifierJob class here will actually be a Struct object. You can create<br />

the code by first creating a new directory called app/jobs and then a new file in it<br />

called comment_notifier_job.rb, using the code you stole from the after_create<br />

method as shown in the following listing.<br />

Listing 16.6 app/jobs/comment_notifier_job.rb<br />

class CommentNotifierJob < Struct.new(:comment_id)<br />

def perform<br />

comment = Comment.find(comment_id)<br />

watchers = comment.ticket.watchers - [comment.user]<br />

watchers.each do |user|<br />

Notifier.comment_updated(comment, user).deliver<br />

end<br />

end<br />

end<br />

In the perform method here, you find the comment based on the comment_id and<br />

then iterate through all the watchers of the comment’s ticket who are not the commenter<br />

themselves, sending them each an email that the ticket has been updated with<br />

a new comment.<br />

By enqueueing this job using the Delayed::Job.enqueue method, the<br />

delayed_job gem will store a marshalled format (actually a YAML string) of this object<br />

in the table, such as this:<br />

--- !ruby/struct:CommentNotifierJob \ncomment_id: 1\n<br />

463

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!