Skip to content

Commit

Permalink
feat(): copy job model into app
Browse files Browse the repository at this point in the history
add loggeable concern too
  • Loading branch information
ldlsegovia committed Nov 19, 2018
1 parent 4e7805a commit 2b170fd
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 72 deletions.
72 changes: 0 additions & 72 deletions app/models/active_job_log/job.rb

This file was deleted.

1 change: 1 addition & 0 deletions lib/active_job_log/engine.rb
Expand Up @@ -9,6 +9,7 @@ class Engine < ::Rails::Engine

initializer "initialize" do
require_relative "./log_ext"
require_relative "./loggeable"
end
end
end
72 changes: 72 additions & 0 deletions lib/active_job_log/loggeable.rb
@@ -0,0 +1,72 @@
module ActiveJobLog
module Loggeable
extend ActiveSupport::Concern

included do
extend Enumerize

STATUSES = %i{queued pending finished failed}

validates :job_id, presence: true

enumerize :status, in: STATUSES, scope: true

serialize :params, Array
serialize :stack_trace, Array

before_save :set_queued_duration
before_save :set_execution_duration
before_save :set_total_duration

def set_queued_duration
return if queued_at.blank? || started_at.blank?
self.queued_duration = (started_at.to_f - queued_at.to_f).to_i
end

def set_execution_duration
return if started_at.blank? || ended_at.blank?
self.execution_duration = (ended_at.to_f - started_at.to_f).to_i
end

def set_total_duration
from = queued_at || started_at
return if from.blank? || ended_at.blank?
self.total_duration = (ended_at.to_f - from.to_f).to_i
end
end

module ClassMethods
def update_job!(job_id, status, params = {})
params.merge!(status_to_params(status))
job = find_or_create_job(job_id)
job.update_attributes!(params)
job
end

def find_or_create_job(job_id)
where(job_id: job_id).where.not(status: :failed).last || create(job_id: job_id)
end

def status_to_params(status)
time_attr = infer_duration_attr_from_status(status)
{
time_attr => DateTime.current,
status: status
}
end

def infer_duration_attr_from_status(status)
case status
when :queued
:queued_at
when :pending
:started_at
when :finished, :failed
:ended_at
else
fail "invalid status"
end
end
end
end
end
4 changes: 4 additions & 0 deletions lib/generators/active_job_log/install/install_generator.rb
Expand Up @@ -13,6 +13,10 @@ def mount_routes
end
end

def copy_job_model
copy_file "job_model.rb", "app/models/active_job_log/job.rb"
end

def copy_engine_migrations
rake "railties:install:migrations"
end
Expand Down
5 changes: 5 additions & 0 deletions lib/generators/active_job_log/install/templates/job_model.rb
@@ -0,0 +1,5 @@
module ActiveJobLog
class Job < ApplicationRecord
include Loggeable
end
end
5 changes: 5 additions & 0 deletions spec/dummy/app/models/active_job_log/job.rb
@@ -0,0 +1,5 @@
module ActiveJobLog
class Job < ApplicationRecord
include Loggeable
end
end

0 comments on commit 2b170fd

Please sign in to comment.