lib/lev/background_job.rb in lev-5.0.0 vs lib/lev/background_job.rb in lev-6.0.0

- old
+ new

@@ -21,11 +21,11 @@ ].freeze def initialize(attrs = {}) @id = attrs[:id] || attrs['id'] || SecureRandom.uuid @status = attrs[:status] || attrs['status'] || STATE_UNKNOWN - @progress = attrs[:progress] || attrs['progress'] || set_progress(0) + @progress = attrs[:progress] || attrs['progress'] || 0 @errors = attrs[:errors] || attrs['errors'] || [] set({ id: id, status: status, progress: progress, @@ -33,12 +33,12 @@ end def self.find(id) attrs = { id: id } - if job = store.fetch(job_key(id)) - attrs.merge!(JSON.parse(job)) + if job = fetch_and_parse(job_key(id)) + attrs.merge!(job) else attrs.merge!(status: STATE_UNKNOWN) end new(attrs) @@ -57,21 +57,26 @@ set(data_to_set) progress end - STATES.each do |state| + (STATES - [STATE_COMPLETED]).each do |state| define_method("#{state}!") do set(status: state) end end + def completed! + set({status: STATE_COMPLETED, progress: 1.0}) + end + def add_error(error, options = { }) options = { is_fatal: false }.merge(options) @errors << { is_fatal: options[:is_fatal], code: error.code, - message: error.message } + message: error.message, + data: error.data } set(errors: @errors) end # Rails compatibility # returns a Hash of all key-value pairs that have been #set() @@ -101,35 +106,39 @@ protected RESERVED_KEYS = [:id, :status, :progress, :errors] def set(incoming_hash) + incoming_hash = incoming_hash.stringify_keys incoming_hash = stored.merge(incoming_hash) incoming_hash.each { |k, v| instance_variable_set("@#{k}", v) } self.class.store.write(job_key, incoming_hash.to_json) track_job_id end def self.store Lev.configuration.job_store end + def self.fetch_and_parse(job_key) + fetched = store.fetch(job_key) + return nil if fetched.nil? + JSON.parse(fetched).stringify_keys! + end + def self.job_ids store.fetch(job_key('lev_job_ids')) || [] end def stored - if found = self.class.store.fetch(job_key) - JSON.parse(found) - else - {} - end + self.class.fetch_and_parse(job_key) || {} end def track_job_id ids = self.class.job_ids + return if ids.include?(@id) ids << @id - self.class.store.write(self.class.job_key('lev_job_ids'), ids.uniq) + self.class.store.write(self.class.job_key('lev_job_ids'), ids) end def job_key self.class.job_key(@id) end