Prevent ruby on rails 3 from parsing JSON post

http, json, post, ruby-on-rails, ruby-on-rails-3

Solution

Parameter parsing is baked pretty deeply inside actionpack's `lib/action_dispatch/middleware/params_parser.rb`.

I'd say the best you're going to get away with is intercepting the request with Rack, something like this.

In `lib/raw_json.rb`

module Rack
  class RawJSON
    def initialize(app)
      @app = app
    end

    def call(env)
      request = Request.new(env)
      if request.content_type =~ /application\/json/i
        # test request.path here to limit your processing to particular actions
        raw_json = env['rack.input'].read
        env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        env['rack.input'] = StringIO.new("raw_json=#{raw_json}")
      end
      return @app.call(env)
    end
  end
end

In `config.ru`, insert this before the call to `run <your app name>::Application`

require 'raw_json'
use Rack::RawJSON

Problem

I have a controller method in Ruby on Rails 3 that accepts application/JSON as the content type. This all works as expected, but I actually do not want rails to automatically parse the JSON in the body of the POST request. This method is acting as a gateway and just shuttles the information in to a queue and could be quite large. I do not want to waste the time processing the data in to the @_params since it's unnecessary. I believe I could get around this by setting the content-type in the header of the request to something else, but I would like to be semantically correct for the HTTP requests. How can I disable this functionality? EDIT: more specifically how can I edit this functionality for just this one route?

Original source

Related problems