docbrown/app/models/data_update_script.rb
Ridhwana 2dad0c42f8
Save Data Update Script errors to database and show them on http://localhost:3000/admin/data_update_scripts (#12348)
* feat: add an error column to the data update script

* feat: save the error to the error field

* feat: save the error when the script fails

* feat: show the script error on the data update script page

* chore: pass the error to mark_as_failed instead of having its own function

* refactor: use presence

* test: ensure that we test an error case of a data update script

* chore: rename errorneous to failing

* test: update some specs, working on the others

* chore: update tests now that there are two files

* chore: change error from a string to a text to allow for more char
2021-01-21 14:48:34 +01:00

75 lines
1.7 KiB
Ruby

class DataUpdateScript < ApplicationRecord
DIRECTORY = Rails.root.join("lib/data_update_scripts").freeze
NAMESPACE = "DataUpdateScripts".freeze
STATUSES = { enqueued: 0, working: 1, succeeded: 2, failed: 3 }.freeze
enum status: STATUSES
validates :file_name, presence: true, uniqueness: true
validates :status, presence: true
class << self
def scripts_to_run
insert_new_scripts
enqueued.order(file_name: :asc)
end
# true if there are more files on disk or any scripts to run, false otherwise
def scripts_to_run?
db_scripts = DataUpdateScript.pluck(:file_name, :status).to_h
return true if filenames.size > db_scripts.size
return true if db_scripts.values.any? { |s| s.to_sym == :enqueued }
false
end
private
def filenames
Dir.glob("*.rb", base: DIRECTORY).map do |f|
File.basename(f, ".rb")
end
end
def insert_new_scripts
now = Time.current
scripts_params = filenames.map do |fn|
{ file_name: fn, created_at: now, updated_at: now }
end
DataUpdateScript.insert_all(scripts_params)
end
end
def mark_as_run!
update!(run_at: Time.current, status: :working)
end
def mark_as_finished!
update!(finished_at: Time.current, status: :succeeded)
end
def mark_as_failed!(err)
update!(
finished_at: Time.current,
status: :failed,
error: "#{err.class}: #{err.message}",
)
end
def file_path
"#{self.class::DIRECTORY}/#{file_name}.rb"
end
def file_class
"#{self.class::NAMESPACE}::#{parsed_file_name.camelcase}".safe_constantize
end
private
def parsed_file_name
file_name.match(/\d{14}_(.*)/)[1]
end
end