Skip to content

Instantly share code, notes, and snippets.

@lenny
Last active August 29, 2015 14:04
Show Gist options
  • Save lenny/c2081005b633cc6f18d4 to your computer and use it in GitHub Desktop.
Save lenny/c2081005b633cc6f18d4 to your computer and use it in GitHub Desktop.
class BackgroundJobWatcher
attr_accessor :mailer, :error_io
class << self
def attempt(job_name, &blk)
new.attempt(job_name, &blk)
end
end
def initialize(opts = {})
self.mailer = opts.fetch(:mailer) { ErrorMailer }
self.error_io = opts.fetch(:error_io) { $stderr }
end
def attempt(job_name, &blk)
blk.call
rescue => e
msg = "#{e.message}\n\t#{e.backtrace.join("\n\t")}"
error_io.puts msg
mailer.notify("#{job_name} failed", msg)
end
end
require 'spec_helper'
require 'stringio'
describe BackgroundJobWatcher do
let(:error_io) { StringIO.new }
let(:mailer) { double('Mailer').as_null_object }
subject { BackgroundJobWatcher.new(:mailer => mailer, :error_io => error_io ) }
describe '#attempt(description, &blk)' do
it 'yields to block' do
i = 0
subject.attempt('foo') { i += 1 }
i.should == 1
end
context 'on failure' do
it 'rescues error' do
subject.attempt('foo') { raise 'some error' }
end
it 'notifies mailer' do
mailer.should_receive(:notify).with('myjob failed', instance_of(String))
subject.attempt('myjob') { raise 'some error' }
end
it 'outputs message to error io' do
subject.attempt('myjob') { raise 'some error' }
error_io.string.should include('some error')
end
end
end
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
Cart.purge_stale(3)
Order.purge_unconfirmed(14)
ActionLogEntry.purge
Logging::ActionLogging.current_user = ::User.new(:login => 'kisbot')
BackgroundJobWatcher.attempt('nightly mailgun import') do
MailerService.pull_bounces
MailerService.pull_complaints
MailerService.pull_unsubscribes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment