# frozen_string_literal: true module Cron # # Value object for a cron tab entry # class JobTab < Tab FRAMEWORK_CLASSES = %w[Job TrimCollection Command Server Tab JobTab].freeze unless defined? FRAMEWORK_CLASSES # # Validations # validates :name, presence: true, uniqueness: true validate :valid_name class << self # # Pull form system configuration # def from_string(name, value) tab = JobTab.find_or_initialize_by name: name return unless tab.valid? tab.update_from_string(value) tab end def ensure_cron_tabs job_names.each do |job_name| klass = "cron/#{job_name}".camelize.constantize tab = JobTab.find_or_initialize_by name: job_name next if tab.persisted? configure_cron_tab(tab, klass.cron_tab) end purge_cron_tabs end def job_names @job_names ||= Cron.constants.collect do |job| job_name = job.to_s next if FRAMEWORK_CLASSES.include?(job_name) || job_name.end_with?('Test') || job_name.start_with?('Base') job_name.underscore end.compact end private def configure_cron_tab(tab, type) case type when :always tab.update! min: Cron::Tab::WILDCARD, hour: Cron::Tab::WILDCARD when :hourly tab.update! min: 0, hour: Cron::Tab::WILDCARD when :daily tab.update! min: 0, hour: 0 when :weekly tab.update! min: 0, hour: 0, wday: 0 when :monthly tab.update! min: 0, hour: 0, mday: 0 else tab.update_from_string(type) tab.save! end end def purge_cron_tabs JobTab.all.each do |tab| tab.destroy unless job_names.include?(tab.name) end end end # # Update our values based on the value # def update_from_string(value) values = value.split(' ') self.min = values[0] self.hour = values[1] self.mday = values[2] self.month = values[3] self.wday = values[4] end # # Run this job cron tab # def run return unless valid_environment? cron_job_class.perform_later super end # # Is this enabled and a valid environment # def valid_environment? enabled? && cron_job_class.valid_environment? end # # Return the class associated with this job cron tab # def cron_job_class @cron_job_class ||= "cron/#{name}".camelize.constantize end # # Convert back to a standard string value # def to_string [min, hour, mday, month, wday].join(' ') end # # Test the name is the list of jobs discovered # def valid_name errors.add(:name, 'Invalid Tab') unless JobTab.job_names.include?(name) end end end