class Pragma::Operation::Response

Represents an HTTP response. Provides utilities to deal with status codes and such.

Constants

STATUSES

Attributes

entity[RW]

@!attribute [rw] entity

@return [Object] the entity/body of the response

@!attribute [rw] headers

@return [Hash] the headers of the response
headers[RW]

@!attribute [rw] entity

@return [Object] the entity/body of the response

@!attribute [rw] headers

@return [Hash] the headers of the response
status[R]

@!attribute [r] status

@return [Integer|Symbol] the HTTP status code of the response

Public Class Methods

new(status: 200, entity: nil, headers: {}) click to toggle source

Initializes the response.

@param status [Integer|Symbol] the HTTP status code of the response @param entity [Object] the entity/body of the response @param headers [Hash] the headers of the response

# File lib/pragma/operation/response.rb, line 84
def initialize(status: 200, entity: nil, headers: {})
  self.status = status
  self.entity = entity
  self.headers = headers
end

Public Instance Methods

decorate_with(decorator) click to toggle source

Applies a decorator to the response's entity.

@param decorator [Class] the decorator to apply

@return [Response] returns itself for chaining

@example Applying a decorator

response = Pragma::Operation::Response::Ok.new(entity: user).decorate_with(UserDecorator)
# File lib/pragma/operation/response.rb, line 132
def decorate_with(decorator)
  tap do
    self.entity = decorator.represent(entity)
  end
end
failure?() click to toggle source

Returns whether the response has a failed HTTP status code, by checking whether the status code is 4xx or 5xx.

@return [Boolean]

# File lib/pragma/operation/response.rb, line 102
def failure?
  !success?
end
status=(v) click to toggle source

Sets the HTTP status code of the response.

@param v [Symbol|Integer] the status code (e.g. 200/:ok)

@raise [ArgumentError] if an invalid status code is provided

# File lib/pragma/operation/response.rb, line 111
def status=(v)
  case v
  when Integer
    fail ArgumentError, "#{v} is not a valid status code" unless STATUSES[v]
    @status = v
  when Symbol, String
    fail ArgumentError, "#{v} is not a valid status phrase" unless STATUSES.invert[v.to_sym]
    @status = STATUSES.invert[v.to_sym]
  else
    fail ArgumentError, "#status= expects an integer or a symbol, #{v} provided"
  end
end
success?() click to toggle source

Returns whether the response has a successful HTTP status code, by checking whether the status code is 1xx, 2xx or 3xx.

@return [Boolean]

# File lib/pragma/operation/response.rb, line 94
def success?
  %w[1 2 3].include?(@status.to_s[0])
end