Sha256: 1ce86e2d3c19d59f47874851eed908a93c753acfd8c7bc50095fb6bd4d00a4eb

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

module ResourceKit
  class ActionInvoker
    ALLOWED_VERBS = [:get, :post, :put, :delete, :head, :patch, :options]

    def self.call(action, connection, *args)
      raise ArgumentError, "Verb '#{action.verb}' is not allowed" unless action.verb.in?(ALLOWED_VERBS)
      options = args.extract_options!
      resolver = EndpointResolver.new(path: action.path)

      if args.size > 0 and action.verb.in?([:post, :put, :patch])
        # This request is going to have a response body. Handle it.
        response = connection.send(action.verb, resolver.resolve(options)) do |request|
          request.body = construct_body(args.first, action)
        end
      else
        response = connection.send(action.verb, resolver.resolve(options))
      end

      handle_response(response, action)
    end

    def self.handle_response(response, action)
      if handler = action.handlers[response.status]
        handler.call(response)
      else
        response.body
      end
    end

    def self.construct_body(object, action)
      if action.body
        action.body.call(object)
      else
        object.to_s
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
resource_kit-0.0.1 lib/resource_kit/action_invoker.rb