2017-07-24 16:20:53 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-07-10 16:02:12 -04:00
|
|
|
module ActionDispatch
|
|
|
|
class RequestEncoder # :nodoc:
|
2016-11-22 16:22:34 -05:00
|
|
|
class IdentityEncoder
|
|
|
|
def content_type; end
|
|
|
|
def accept_header; end
|
|
|
|
def encode_params(params); params; end
|
|
|
|
def response_parser; -> body { body }; end
|
|
|
|
end
|
|
|
|
|
|
|
|
@encoders = { identity: IdentityEncoder.new }
|
2016-07-10 16:02:12 -04:00
|
|
|
|
|
|
|
attr_reader :response_parser
|
|
|
|
|
2016-11-27 12:06:01 -05:00
|
|
|
def initialize(mime_name, param_encoder, response_parser)
|
2016-07-10 16:02:12 -04:00
|
|
|
@mime = Mime[mime_name]
|
|
|
|
|
|
|
|
unless @mime
|
|
|
|
raise ArgumentError, "Can't register a request encoder for " \
|
|
|
|
"unregistered MIME Type: #{mime_name}. See `Mime::Type.register`."
|
|
|
|
end
|
|
|
|
|
2016-11-22 16:22:34 -05:00
|
|
|
@response_parser = response_parser || -> body { body }
|
|
|
|
@param_encoder = param_encoder || :"to_#{@mime.symbol}".to_proc
|
2016-07-10 16:02:12 -04:00
|
|
|
end
|
|
|
|
|
2016-11-22 16:22:34 -05:00
|
|
|
def content_type
|
|
|
|
@mime.to_s
|
2016-07-10 16:02:12 -04:00
|
|
|
end
|
|
|
|
|
2016-11-22 16:22:34 -05:00
|
|
|
def accept_header
|
2016-07-10 16:02:12 -04:00
|
|
|
@mime.to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
def encode_params(params)
|
2018-07-20 06:48:49 -04:00
|
|
|
@param_encoder.call(params) if params
|
2016-07-10 16:02:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.parser(content_type)
|
2019-03-06 02:38:59 -05:00
|
|
|
type = Mime::Type.lookup(content_type).ref if content_type
|
|
|
|
encoder(type).response_parser
|
2016-07-10 16:02:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.encoder(name)
|
2016-11-22 16:22:34 -05:00
|
|
|
@encoders[name] || @encoders[:identity]
|
2016-07-10 16:02:12 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.register_encoder(mime_name, param_encoder: nil, response_parser: nil)
|
|
|
|
@encoders[mime_name] = new(mime_name, param_encoder, response_parser)
|
|
|
|
end
|
|
|
|
|
|
|
|
register_encoder :json, response_parser: -> body { JSON.parse(body) }
|
|
|
|
end
|
|
|
|
end
|