lib/restfulness/request.rb in restfulness-0.3.2 vs lib/restfulness/request.rb in restfulness-0.3.3
- old
+ new
@@ -1,14 +1,17 @@
module Restfulness
# Simple, indpendent, request interface for dealing with the incoming information
- # in a request.
+ # in a request.
#
# Currently wraps around the information provided in a Rack Request object.
class Request
include Requests::Authorization
+ # Expose rack env to interact with rack middleware
+ attr_accessor :env
+
# Who does this request belong to?
attr_reader :app
# The HTTP action being handled
attr_accessor :action
@@ -53,23 +56,36 @@
def sanitized_query_string
@sanitized_query ||= uri.query ? Sanitizer.sanitize_query_string(uri.query) : ''
end
+ def accept
+ if headers[:accept]
+ @accept ||= Headers::Accept.new(headers[:accept])
+ end
+ end
+
+ def content_type
+ if headers[:content_type]
+ @content_type ||= Headers::MediaType.new(headers[:content_type])
+ end
+ end
+
def params
@params ||= begin
- if body.nil? || body.length == 0
- {}
- else
- case headers[:content_type]
- when /application\/json/
- @params = params_from_json(body)
- when /application\/x\-www\-form\-urlencoded/
- @params = params_from_form(body)
+ data = body_to_string || ""
+ if data.length > 0
+ if content_type && content_type.json?
+ params_from_json(data)
+ elsif content_type && content_type.form?
+ params_from_form(data)
else
+ # Body provided with no or invalid content type
raise HTTPException.new(406)
end
+ else
+ {}
end
end
end
def sanitized_params
@@ -88,18 +104,30 @@
end
end
protected
- def params_from_json(body)
- MultiJson.decode(body)
+ def body_to_string
+ unless body.nil?
+ # Sometimes the body can be a StringIO, Tempfile, or some other freakish IO.
+ if body.respond_to?(:read)
+ body.read
+ else
+ body
+ end
+ else
+ ""
+ end
+ end
+
+ def params_from_json(data)
+ MultiJson.decode(data)
rescue MultiJson::LoadError
- raise HTTPException.new(400)
+ raise HTTPException.new(400, "Invalid JSON in request body")
end
- def params_from_form(body)
- # Sometimes the body can be a StringIO
- Rack::Utils.parse_query(body.is_a?(StringIO) ? body.read : body)
+ def params_from_form(data)
+ Rack::Utils.parse_query(data)
end
end
end