lib/roda/plugins/json.rb in roda-2.9.0 vs lib/roda/plugins/json.rb in roda-2.10.0
- old
+ new
@@ -1,5 +1,7 @@
+# frozen-string-literal: true
+
require 'json'
class Roda
module RodaPlugins
# The json plugin allows match blocks to return
@@ -42,14 +44,20 @@
# If you need the request information during serialization, such
# as HTTP headers or query parameters, you can pass in the
# +:include_request+ option, which will pass in the request
# object as the second argument when calling the serializer.
#
- # plugin :json, include_request=>true, serializer=>proc{|o, request| ...}
+ # plugin :json, :include_request=>true, :serializer=>proc{|o, request| ...}
+ #
+ # The default content-type is 'application/json', but you can change that
+ # using the +:content_type+ option:
+ #
+ # plugin :json, :content_type=>'application/xml'
module Json
OPTS = {}.freeze
DEFAULT_SERIALIZER = lambda{|o| o.to_json}
+ DEFAULT_CONTENT_TYPE = 'application/json'.freeze
# Set the classes to automatically convert to JSON, and the serializer to use.
def self.configure(app, opts=OPTS)
classes = opts[:classes] || [Array, Hash]
app.opts[:json_result_classes] ||= []
@@ -58,10 +66,12 @@
app.opts[:json_result_classes].freeze
app.opts[:json_result_serializer] = opts[:serializer] || app.opts[:json_result_serializer] || DEFAULT_SERIALIZER
app.opts[:json_result_include_request] = opts[:include_request] || app.opts[:json_result_include_request]
+
+ app.opts[:json_result_content_type] = opts[:content_type] || DEFAULT_CONTENT_TYPE
end
module ClassMethods
# The classes that should be automatically converted to json
def json_result_classes
@@ -69,20 +79,19 @@
end
end
module RequestMethods
CONTENT_TYPE = 'Content-Type'.freeze
- APPLICATION_JSON = 'application/json'.freeze
private
# If the result is an instance of one of the json_result_classes,
# convert the result to json and return it as the body, using the
# application/json content-type.
def block_result_body(result)
case result
when *roda_class.json_result_classes
- response[CONTENT_TYPE] = APPLICATION_JSON
+ response[CONTENT_TYPE] ||= roda_class.opts[:json_result_content_type]
convert_to_json(result)
else
super
end
end