Created
July 9, 2017 23:35
-
-
Save danielfone/6727efcc6a071b15b3dec67a74386740 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActiveJobLog < ApplicationRecord | |
enum status: { | |
queued: 'queued', | |
working: 'working', | |
finished: 'finished', | |
failed: 'failed', | |
} | |
def active? | |
queued? || working? | |
end | |
def queued! | |
self.queued_at = Time.current | |
super | |
end | |
def working! | |
self.started_at = Time.current | |
super | |
end | |
def finished! | |
self.finished_at = Time.current | |
super | |
end | |
def failed! | |
self.finished_at = Time.current | |
super | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module JobLogging | |
mattr_accessor :rescue_errors | |
self.rescue_errors = true | |
def self.included(base) | |
base.cattr_accessor :job_type | |
base.before_enqueue :mark_as_queued | |
base.before_perform :mark_as_working | |
base.after_perform :mark_as_finished | |
base.rescue_from StandardError, with: :mark_as_failed | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def logs | |
ActiveJobLog.where(job_type: job_type) | |
end | |
def last_log | |
logs.last | |
end | |
def job_type | |
name.parameterize | |
end | |
end | |
private | |
# I'm ok with the race-condition here | |
def log | |
@log ||= ActiveJobLog.find_or_create_by(job_id: job_id, job_type: job_type) | |
end | |
def mark_as_queued | |
log.queued! | |
end | |
def mark_as_working | |
log.working! | |
end | |
def mark_as_finished | |
log.finished! | |
end | |
def mark_as_failed(error) | |
raise unless rescue_errors | |
log.job_errors << error.message | |
log.failed! | |
Bugsnag.notify(error) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment