diff --git a/lib/apia/rack.rb b/lib/apia/rack.rb index 761617e..f9fdf87 100644 --- a/lib/apia/rack.rb +++ b/lib/apia/rack.rb @@ -152,6 +152,20 @@ def triplet_for_exception(exception) class << self + # Return a triplet for the given body. + # + # @param body [Hash, Array] + # @param status [Integer] + # @param headers [Hash] + # @return [Array] + def plain_triplet(body, status: 200, headers: {}) + [ + status, + headers.merge('content-type' => 'text/plain', 'content-length' => body.bytesize.to_s), + [body] + ] + end + # Return a JSON-ready triplet for the given body. # # @param body [Hash, Array] diff --git a/lib/apia/response.rb b/lib/apia/response.rb index 8325e06..6f2659d 100644 --- a/lib/apia/response.rb +++ b/lib/apia/response.rb @@ -10,6 +10,7 @@ class Response attr_reader :fields attr_reader :headers attr_writer :body + attr_writer :type def initialize(request, endpoint) @request = request @@ -53,11 +54,18 @@ def body @body || hash end + def type + @type || :json + end + # Return the rack triplet for this response # # @return [Array] def rack_triplet - Rack.json_triplet(body, headers: @headers, status: @status) + return Rack.json_triplet(body, headers: @headers, status: @status) if type == :json + return Rack.plain_triplet(body, headers: @headers, status: @status) if type == :plain + + raise "Unknown response type '#{type}'" end end