2010-04-21 00:58:30 -04:00
|
|
|
require 'active_support/core_ext/hash/conversions'
|
2009-12-22 18:11:21 -05:00
|
|
|
require 'action_dispatch/http/request'
|
2010-04-21 00:58:58 -04:00
|
|
|
require 'active_support/core_ext/hash/indifferent_access'
|
2009-04-22 19:48:58 -04:00
|
|
|
|
2009-01-27 19:54:01 -05:00
|
|
|
module ActionDispatch
|
2009-01-17 21:29:50 -05:00
|
|
|
class ParamsParser
|
2012-08-27 17:46:53 -04:00
|
|
|
class ParseError < StandardError
|
|
|
|
attr_reader :original_exception
|
|
|
|
|
|
|
|
def initialize(message, original_exception)
|
|
|
|
super(message)
|
|
|
|
@original_exception = original_exception
|
|
|
|
end
|
|
|
|
end
|
2012-08-24 12:08:06 -04:00
|
|
|
|
2015-07-09 17:56:26 -04:00
|
|
|
DEFAULT_PARSERS = {
|
|
|
|
Mime::JSON => lambda { |raw_post|
|
|
|
|
data = ActiveSupport::JSON.decode(raw_post)
|
|
|
|
data = {:_json => data} unless data.is_a?(Hash)
|
|
|
|
Request::Utils.deep_munge(data).with_indifferent_access
|
|
|
|
}
|
|
|
|
}
|
2009-01-17 21:29:50 -05:00
|
|
|
|
2009-08-21 17:49:33 -04:00
|
|
|
def initialize(app, parsers = {})
|
|
|
|
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
|
2009-01-17 21:29:50 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
2015-07-09 18:12:24 -04:00
|
|
|
default = env["action_dispatch.request.request_parameters"]
|
2015-07-09 18:13:38 -04:00
|
|
|
env["action_dispatch.request.request_parameters"] = parse_formatted_parameters(env, @parsers, default)
|
2009-01-17 21:29:50 -05:00
|
|
|
|
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2015-07-09 18:13:38 -04:00
|
|
|
def parse_formatted_parameters(env, parsers, default)
|
2009-01-17 21:29:50 -05:00
|
|
|
request = Request.new(env)
|
|
|
|
|
2015-07-09 18:12:24 -04:00
|
|
|
return default if request.content_length.zero?
|
2009-01-17 21:29:50 -05:00
|
|
|
|
2015-07-09 18:13:38 -04:00
|
|
|
strategy = parsers.fetch(request.content_mime_type) { return default }
|
2009-01-17 21:29:50 -05:00
|
|
|
|
2015-07-09 17:56:26 -04:00
|
|
|
strategy.call(request.raw_post)
|
2009-01-17 21:29:50 -05:00
|
|
|
|
2014-11-23 16:04:31 -05:00
|
|
|
rescue => e # JSON or Ruby code block errors
|
2012-08-27 17:46:53 -04:00
|
|
|
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
|
2009-08-11 00:56:46 -04:00
|
|
|
|
2012-08-27 17:46:53 -04:00
|
|
|
raise ParseError.new(e.message, e)
|
2009-01-17 21:29:50 -05:00
|
|
|
end
|
|
|
|
|
2011-11-24 14:37:48 -05:00
|
|
|
def logger(env)
|
2011-12-21 13:49:25 -05:00
|
|
|
env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
|
2009-08-11 00:56:46 -04:00
|
|
|
end
|
2009-01-17 21:29:50 -05:00
|
|
|
end
|
2010-04-07 14:42:07 -04:00
|
|
|
end
|