Sha256: e0eb87afaaa14dee39f87b2fd1b15ac206ce0911373bcb55667bb9860f7bd1cf

Contents?: true

Size: 1.57 KB

Versions: 78

Compression:

Stored size: 1.57 KB

Contents

module Scrivito
  class Task
    def self.find(id)
      new(id: id)
    end

    attr_reader :id

    def initialize(params = nil)
      return update(params) if params

      response = yield
      if params = extract_params(response)
        update(params)
      else
        update(status: 'success', result: response)
      end
    rescue ClientError => e
      update(status: 'error', message: e.message, code: e.backend_code)
    end

    def open?
      @status == 'open'
    end

    def success?
      @status == 'success'
    end

    def error?
      @status == 'error'
    end

    def result
      case
      when success? then @result
      when error?   then raise ClientError.new(@message, backend_code: @code)
      else
        poll
        result
      end
    end

    private

    def extract_params(response)
      if response.is_a?(Hash) && response.keys == ['task'] && response['task'].is_a?(Hash)
        response['task']
      end
    end

    def reload
      task_data = CmsRestApi.task_unaware_request(:get, "tasks/#{@id}")
      update(task_data)
    end

    def update(task_data)
      task_data = task_data.with_indifferent_access

      @id      = task_data[:id]      if task_data[:id]
      @status  = task_data[:status]  if task_data[:status]
      @result  = task_data[:result]  if task_data[:result]
      @message = task_data[:message] if task_data[:message]
      @code    = task_data[:code]    if task_data[:code]

      reload unless @status
    end

    def poll
      loop do
        sleep 2
        reload
        break unless open?
      end
    end
  end
end

Version data entries

78 entries across 78 versions & 1 rubygems

Version Path
scrivito_sdk-1.7.0 lib/scrivito/task.rb
scrivito_sdk-1.7.0.rc2 lib/scrivito/task.rb
scrivito_sdk-1.5.5 lib/scrivito/task.rb
scrivito_sdk-1.6.1 lib/scrivito/task.rb
scrivito_sdk-1.6.1.rc1 lib/scrivito/task.rb
scrivito_sdk-1.5.5.rc1 lib/scrivito/task.rb
scrivito_sdk-1.4.3 lib/scrivito/task.rb
scrivito_sdk-1.5.4 lib/scrivito/task.rb
scrivito_sdk-1.7.0.rc1 lib/scrivito/task.rb
scrivito_sdk-1.6.0 lib/scrivito/task.rb
scrivito_sdk-1.6.0.rc5 lib/scrivito/task.rb
scrivito_sdk-1.5.4.rc1 lib/scrivito/task.rb
scrivito_sdk-1.6.0.rc4 lib/scrivito/task.rb
scrivito_sdk-1.6.0.rc3 lib/scrivito/task.rb
scrivito_sdk-1.5.3 lib/scrivito/task.rb
scrivito_sdk-1.6.0.rc2 lib/scrivito/task.rb
scrivito_sdk-1.5.3.rc1 lib/scrivito/task.rb
scrivito_sdk-1.6.0.rc1 lib/scrivito/task.rb
scrivito_sdk-1.5.2 lib/scrivito/task.rb
scrivito_sdk-1.5.2.rc1 lib/scrivito/task.rb