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
|
|
|
|
2013-02-19 15:41:03 -05:00
|
|
|
DEFAULT_PARSERS = { Mime::JSON => :json }
|
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)
|
|
|
|
if params = parse_formatted_parameters(env)
|
2009-04-30 14:45:12 -04:00
|
|
|
env["action_dispatch.request.request_parameters"] = params
|
2009-01-17 21:29:50 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def parse_formatted_parameters(env)
|
|
|
|
request = Request.new(env)
|
|
|
|
|
|
|
|
return false if request.content_length.zero?
|
|
|
|
|
2013-02-19 15:41:03 -05:00
|
|
|
strategy = @parsers[request.content_mime_type]
|
2009-01-17 21:29:50 -05:00
|
|
|
|
|
|
|
return false unless strategy
|
|
|
|
|
|
|
|
case strategy
|
2009-12-20 21:37:09 -05:00
|
|
|
when Proc
|
|
|
|
strategy.call(request.raw_post)
|
|
|
|
when :json
|
2013-07-07 18:32:22 -04:00
|
|
|
data = ActiveSupport::JSON.decode(request.raw_post)
|
2010-04-07 14:12:47 -04:00
|
|
|
data = {:_json => data} unless data.is_a?(Hash)
|
2013-05-30 14:26:37 -04:00
|
|
|
Request::Utils.deep_munge(data).with_indifferent_access
|
2009-12-20 21:37:09 -05:00
|
|
|
else
|
|
|
|
false
|
2009-01-17 21:29:50 -05:00
|
|
|
end
|
2013-02-19 15:41:03 -05:00
|
|
|
rescue Exception => 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
|