lib/grape/middleware/base.rb in grape-0.2.1.1 vs lib/grape/middleware/base.rb in grape-0.2.2
- old
+ new
@@ -1,5 +1,6 @@
+require 'active_support/ordered_hash'
require 'multi_json'
require 'multi_xml'
module Grape
module Middleware
@@ -42,18 +43,18 @@
Rack::Response.new(@app_response)
end
module Formats
-
- CONTENT_TYPES = {
- :xml => 'application/xml',
- :json => 'application/json',
- :atom => 'application/atom+xml',
- :rss => 'application/rss+xml',
- :txt => 'text/plain'
- }
+ # Content types are listed in order of preference.
+ CONTENT_TYPES = ActiveSupport::OrderedHash[
+ :xml, 'application/xml',
+ :json, 'application/json',
+ :atom, 'application/atom+xml',
+ :rss, 'application/rss+xml',
+ :txt, 'text/plain',
+ ]
FORMATTERS = {
:json => :encode_json,
:txt => :encode_txt,
:xml => :encode_xml
}
@@ -68,14 +69,10 @@
def parsers
PARSERS.merge(options[:parsers] || {})
end
- def content_type_for(format)
- Hash.new(content_types)[format.to_sym]
- end
-
def content_types
CONTENT_TYPES.merge(options[:content_types] || {})
end
def content_type
@@ -112,21 +109,33 @@
def decode_json(object)
MultiJson.load(object)
end
- def encode_json(object)
- return object if object.is_a?(String)
+ def serializable?(object)
+ object.respond_to?(:serializable_hash) ||
+ object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false) ||
+ object.kind_of?(Hash)
+ end
+ def serialize(object)
if object.respond_to? :serializable_hash
- MultiJson.dump(object.serializable_hash)
+ object.serializable_hash
elsif object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false)
- MultiJson.dump(object.map {|o| o.serializable_hash })
- elsif object.respond_to? :to_json
- object.to_json
+ object.map {|o| o.serializable_hash }
+ elsif object.kind_of?(Hash)
+ object.inject({}) { |h,(k,v)| h[k] = serialize(v); h }
else
- MultiJson.dump(object)
+ object
end
+ end
+
+ def encode_json(object)
+ return object if object.is_a?(String)
+ return MultiJson.dump(serialize(object)) if serializable?(object)
+ return object.to_json if object.respond_to?(:to_json)
+
+ MultiJson.dump(object)
end
def encode_txt(object)
object.respond_to?(:to_txt) ? object.to_txt : object.to_s
end