lib/webmachine/decision/helpers.rb in webmachine-1.2.2 vs lib/webmachine/decision/helpers.rb in webmachine-1.3.0
- old
+ new
@@ -1,18 +1,21 @@
-require 'stringio'
+require 'stringio'
require 'time'
require 'webmachine/streaming'
require 'webmachine/media_type'
require 'webmachine/quoted_string'
require 'webmachine/etags'
+require 'webmachine/header_negotiation'
+require 'webmachine/constants'
module Webmachine
module Decision
# Methods that assist the Decision {Flow}.
module Helpers
include QuotedString
include Streaming
+ include HeaderNegotiation
# Determines if the response has a body/entity set.
def has_response_body?
!response.body.nil? && !response.body.empty?
end
@@ -24,12 +27,12 @@
end
# Encodes the body in the selected charset and encoding.
def encode_body
body = response.body
- chosen_charset = metadata['Charset']
- chosen_encoding = metadata['Content-Encoding']
+ chosen_charset = metadata[CHARSET]
+ chosen_encoding = metadata[CONTENT_ENCODING]
charsetter = resource.charsets_provided && resource.charsets_provided.find {|c,_| c == chosen_charset }.last || :charset_nop
encoder = resource.encodings_provided[chosen_encoding]
response.body = case body
when String # 1.8 treats Strings as Enumerable
resource.send(encoder, resource.send(charsetter, body))
@@ -45,14 +48,14 @@
else
resource.send(encoder, resource.send(charsetter, body))
end
end
if body_is_fixed_length?
- set_content_length
+ ensure_content_length(response)
else
- response.headers.delete 'Content-Length'
- response.headers['Transfer-Encoding'] = 'chunked'
+ response.headers.delete CONTENT_LENGTH
+ response.headers[TRANSFER_ENCODING] = 'chunked'
end
end
# Assists in receiving request bodies
def accept_helper
@@ -83,40 +86,9 @@
if expires = resource.expires
response.headers['Expires'] = expires.httpdate
end
if modified = resource.last_modified
response.headers['Last-Modified'] = modified.httpdate
- end
- end
-
- # Ensures that responses have an appropriate Content-Length
- # header
- def ensure_content_length
- case
- when response.headers['Transfer-Encoding']
- return
- when [204, 205, 304].include?(response.code)
- response.headers.delete 'Content-Length'
- when has_response_body?
- set_content_length
- else
- response.headers['Content-Length'] = '0'
- end
- end
-
- # Ensures that responses have an appropriate Date header
- def ensure_date_header
- if (200..499).include?(response.code)
- response.headers['Date'] ||= Time.now.httpdate
- end
- end
-
- # Sets the Content-Length header on the response
- def set_content_length
- if response.body.respond_to?(:bytesize)
- response.headers['Content-Length'] = response.body.bytesize.to_s
- else
- response.headers['Content-Length'] = response.body.length.to_s
end
end
# Determines whether the response is of a fixed lenghth, i.e. it
# is a String or IO with known size.