lib/resourceful/resource.rb in paul-resourceful-0.5.4 vs lib/resourceful/resource.rb in paul-resourceful-0.6.0
- old
+ new
@@ -3,11 +3,10 @@
module Resourceful
class Resource
attr_reader :accessor
- attr_accessor :default_header
# Build a new resource for a uri
#
# @param accessor<HttpAccessor>
# The parent http accessor
@@ -28,10 +27,14 @@
def effective_uri
@uris.first
end
alias uri effective_uri
+ def default_header(temp_defaults = {})
+ @default_header.merge(temp_defaults)
+ end
+
# Returns the host for this Resource's current uri
def host
Addressable::URI.parse(uri).host
end
@@ -93,11 +96,10 @@
#
# @raise [ArgumentError] unless :content-type is specified in options
# @raise [UnsuccessfulHttpRequestError] unless the request is a
# success, ie the final request returned a 2xx response code
def post(data = nil, header = {})
- check_content_type_exists(data, header)
request(:post, data, header)
end
# :call-seq:
# put(data = "", :content_type => mime_type)
@@ -114,11 +116,10 @@
#
# @raise [ArgumentError] unless :content-type is specified in options
# @raise [UnsuccessfulHttpRequestError] unless the request is a
# success, ie the final request returned a 2xx response code
def put(data, header = {})
- check_content_type_exists(data, header)
request(:put, data, header)
end
# Performs a DELETE on the resource, following redirects as neccessary.
#
@@ -135,20 +136,35 @@
end
private
# Ensures that the request has a content type header
- # TODO Move this to request
- def check_content_type_exists(body, header)
- if body
- raise MissingContentType unless header.has_key?(:content_type) or default_header.has_key?(:content_type)
+ def ensure_content_type(body, header)
+ return if header.has_key?('Content-Type')
+
+ if body.respond_to?(:content_type)
+ header['Content-Type'] = body.content_type
+ return
end
+
+ return if default_header.has_key?('Content-Type')
+
+ # could not figure it out
+ raise MissingContentType
end
# Actually make the request
def request(method, data, header)
- log_request_with_time "#{method.to_s.upcase} [#{uri}]" do
- request = Request.new(method, self, data, default_header.merge(header))
+ header = default_header.merge(header)
+ ensure_content_type(data, header) if data
+
+ data = StringIO.new(data) if data.kind_of?(String)
+
+ logger.debug { header.map {|k,v| "#{k}: #{v}"}.join("\n\t\t") }
+ logger.debug { data = StringIO.new(data.read); data.string } if data
+
+ log_request_with_time "#{method.to_s.upcase} [#{uri}]" do
+ request = Request.new(method, self, data, header)
request.fetch_response
end
end
# Log it took the time to make the request