lib/m2r/response.rb in m2r-1.0.0 vs lib/m2r/response.rb in m2r-2.0.0

- old
+ new

@@ -1,13 +1,16 @@ require 'm2r' +require 'm2r/http/close' require 'm2r/response/content_length' +require 'm2r/response/to_request' module M2R # Simplest possible abstraction layer over HTTP request # # @api public class Response + include HTTP::Close # @private VERSION = "HTTP/1.1".freeze # @private @@ -64,39 +67,82 @@ 503 => 'Service Unavailable', 504 => 'Gateway Timeout', } STATUS_CODES.freeze - # @return [Fixnum] HTTP Status code - attr_reader :status + attr_reader :reason - # @return [Hash, Headers] Collection of response HTTP Headers - attr_reader :headers + def initialize + status(200) + headers(Headers.new) + body("") + http_version(VERSION) + end - # @return [String] HTTP Body - attr_reader :body + # @param [Fixnum, #to_i] value HTTP status code + def status(value = GETTER) + if value == GETTER + @status + else + @status = value.to_i + @reason = STATUS_CODES[@status] + self + end + end - # @return [String] HTTP Status code description - attr_reader :reason + # @param [Hash] value HTTP headers + def headers(value = GETTER) + if value == GETTER + @headers + else + @headers = value + self + end + end - # @param [Fixnum, #to_i] status HTTP status code - # @param [Hash] headers HTTP headers - # @param [String, nil] body HTTP body - def initialize(status, headers, body = nil) - @status = status.to_i - @headers = headers - @body = body || "" - @reason = STATUS_CODES[status.to_i] + # @param [Hash] header HTTP header key + # @param [Hash] value HTTP header value + def header(header, value = GETTER) + if value == GETTER + @headers[header] + else + @headers[header] = value + self + end end + # @param [String, nil] value HTTP body + def body(value = GETTER) + if value == GETTER + @body + else + @body = value + self + end + end + + # @param [String, nil] version HTTP body + def http_version(value = GETTER) + if value == GETTER + @version + else + @version = value + self + end + end + # @return [String] HTTP Response def to_s - response = "#{VERSION} #{status} #{reason}#{CRLF}" + response = "#{http_version} #{status} #{reason}#{CRLF}" unless headers.empty? response << headers.map { |h, v| "#{h}: #{v}" }.join(CRLF) << CRLF end response << CRLF - response << body + response << body.to_s response end + + protected + + GETTER = Object.new end end