1
0
Fork 0
mirror of https://github.com/rest-client/rest-client.git synced 2022-11-09 13:49:40 -05:00
rest-client--rest-client/lib/restclient/response.rb
Andy Brody de03c9d4d1 Use URI.get_encoding to look up encodings.
Use the (undocumented) URI.get_encoding method introduced in Ruby 2.1 to
look up encodings by the aliases specified in HTML5. This means that the
behavior will differ slightly between versions of Ruby, but the
encodings selected are largely compatible.

For example, `ISO-8859-1` is an alias for `Windows-1252` per the HTML5
specification, while in ruby versions < 2.1 it will be used as is. These
two encodings are largely compatible, and the alias exists due to
servers that return a `charset=ISO-8859-1` when they actually are using
`Windows-1252`.

Other aliases that differ include `shift_jis` (rendered as
`Windows-31J`) and `euc-jp` (rendered as `CP51932`).
2015-11-16 15:23:08 -08:00

85 lines
2 KiB
Ruby

module RestClient
# A Response from RestClient, you can access the response body, the code or the headers.
#
class Response < String
include AbstractResponse
# Return the HTTP response body.
#
# Future versions of RestClient will deprecate treating response objects
# directly as strings, so it will be necessary to call `.body`.
#
# @return [String]
#
def body
# Benchmarking suggests that "#{self}" is fastest, and that caching the
# body string in an instance variable doesn't make it enough faster to be
# worth the extra memory storage.
String.new(self)
end
# Convert the HTTP response body to a pure String object.
#
# @return [String]
def to_s
body
end
# Convert the HTTP response body to a pure String object.
#
# @return [String]
def to_str
body
end
def inspect
"<RestClient::Response #{code.inspect} #{body_truncated(10).inspect}>"
end
def self.create(body, net_http_res, args, request)
result = self.new(body || '')
result.response_set_vars(net_http_res, args, request)
fix_encoding(result)
result
end
private
# Automatically set the encoding of the response object based on the
# presence of a Content-Type... charset header.
#
# If a charset is found and represents a valid encoding, call
# force_encoding on the response to alter it to the correct representation.
#
# @param [Response] response
#
# @return [Encoding,nil]
#
def self.fix_encoding(response)
charset = RestClient::Utils.get_encoding_from_headers(response.headers)
return unless charset
encoding = RestClient::Utils.find_encoding(charset)
if encoding
response.force_encoding(encoding)
elsif RestClient.log
RestClient.log << "No such encoding: #{charset.inspect}"
end
encoding
end
def body_truncated(length)
if body.length > length
body[0..length] + '...'
else
body
end
end
end
end