lib/roda/plugins/json.rb in roda-2.2.0 vs lib/roda/plugins/json.rb in roda-2.3.0

- old
+ new

@@ -30,20 +30,38 @@ # By default, only arrays and hashes are handled, but you # can specifically set the allowed classes to json by adding # using the :classes option when loading the plugin: # # plugin :json, :classes=>[Array, Hash, Sequel::Model] + # + # By default objects are serialized with +to_json+, but you + # can pass in a custom serializer, which can be any object + # that responds to +call(object)+. + # + # plugin :json, :serializer=>proc{|o| o.to_json(root: true)} + # + # 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| ...} module Json OPTS = {}.freeze + DEFAULT_SERIALIZER = lambda{|o| o.to_json} - # Set the classes to automatically convert to JSON + # 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] ||= [] app.opts[:json_result_classes] += classes app.opts[:json_result_classes].uniq! 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] end module ClassMethods # The classes that should be automatically converted to json def json_result_classes @@ -69,12 +87,14 @@ super end end # Convert the given object to JSON. Uses to_json by default, - # but can be overridden to use a different implementation. + # but can use a custom serializer passed to the plugin. def convert_to_json(obj) - obj.to_json + args = [obj] + args << self if roda_class.opts[:json_result_include_request] + roda_class.opts[:json_result_serializer].call(*args) end end end register_plugin(:json, Json)