lib/rocket_job/plugins/singleton.rb in rocketjob-3.5.1 vs lib/rocket_job/plugins/singleton.rb in rocketjob-3.5.2
- old
+ new
@@ -1,24 +1,29 @@
require 'active_support/concern'
module RocketJob
module Plugins
- # Prevent more than one instance of this job class from running at a time
+ # Prevent this job from being saved if another is running, queued, or paused.
module Singleton
extend ActiveSupport::Concern
included do
- # Validation prevents a new job from being saved while one is already running
- validates_each :state do |record, attr, _value|
- if (record.running? || record.queued? || record.paused?) && record.rocket_job_singleton_active?
- record.errors.add(attr, "Another instance of #{record.class.name} is already queued or running")
- end
- end
+ validate :rocket_job_singleton_check
+ end
- # Returns [true|false] whether another instance of this job is already active
- def rocket_job_singleton_active?
- self.class.where(:state.in => %i[running queued], :id.ne => id).exists?
- end
+ # Returns [true|false] whether another instance of this job is already active
+ def rocket_job_singleton_active?
+ self.class.where(:state.in => %i[running queued], :id.ne => id).exists?
end
+
+ private
+
+ # Validation prevents a new job from being saved while one is already running
+ def rocket_job_singleton_check
+ return unless (running? || queued? || paused?) && rocket_job_singleton_active?
+
+ errors.add(:state, "Another instance of #{self.class.name} is already running, queued, or paused")
+ end
+
end
end
end