Sha256: 959619c86ae03356b143c34fff304bb7c2baa1039705eeea367adf3c52d3f4fb

Contents?: true

Size: 1.86 KB

Versions: 12

Compression:

Stored size: 1.86 KB

Contents

module Acfs

  # @api private
  #
  # Describes a CRUD operation. Handle request creation and response
  # processing as well as error handling and stubbing.
  #
  class Operation
    attr_reader :action, :params, :resource, :data, :callback
    delegate :service, to: :resource
    delegate :call, to: :callback

    def initialize(resource, action, opts = {}, &block)
      @resource = resource
      @action   = action.to_sym

      # Operations can be delayed so dup params and data to avoid
      # later in-place changes by modifying passed hash
      @params   = (opts[:params] || {}).dup
      @data     = (opts[:data]   || {}).dup

      @callback = block

      raise ArgumentError, 'ID parameter required for READ, UPDATE and DELETE operation.' if single? and id.nil?
    end

    def single?
      [:read, :update, :delete].include? action
    end

    def synchronous?
      [:update, :delete, :create].include? action
    end

    def id
      # TODO
      @id ||= params.delete(:id) || data[:id]
    end

    def full_params
      id ? params.merge(id: id) : params
    end

    def url
      single? ? resource.url(id) : resource.url
    end

    def method
      { read: :get, list: :get, update: :put, create: :post, delete: :delete }[action]
    end

    def request
      request = ::Acfs::Request.new url, method: method, params: params, data: data
      request.on_complete do |response|
        handle_failure response unless response.success?
        callback.call response.data
      end
      request
    end

    def handle_failure(response)
      case response.code
        when 404
          raise ::Acfs::ResourceNotFound.new response: response
        when 422
          raise ::Acfs::InvalidResource.new response: response, errors: response.data.try(:[], 'errors')
        else
          raise ::Acfs::ErroneousResponse.new response: response
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
acfs-0.25.0.1.b232 lib/acfs/operation.rb
acfs-0.25.0.1.b229 lib/acfs/operation.rb
acfs-0.25.0.1.b228 lib/acfs/operation.rb
acfs-0.25.0.1.b227 lib/acfs/operation.rb
acfs-0.25.0.1.b226 lib/acfs/operation.rb
acfs-0.25.0.1.b225 lib/acfs/operation.rb
acfs-0.25.0.1.b223 lib/acfs/operation.rb
acfs-0.25.0.1.b221 lib/acfs/operation.rb
acfs-0.25.0.1.b217 lib/acfs/operation.rb
acfs-0.25.0 lib/acfs/operation.rb
acfs-0.24.0.1.b216 lib/acfs/operation.rb
acfs-0.24.0.1.b214 lib/acfs/operation.rb