Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Rails parse a posted string as json without sending the 'Content-type: application/json' header?

Rails changes behaviour at several levels when the header 'Content-type: application/json' is sent:

  • submitted post body is parsed as json instead of just a string parameter
  • wrap_parameters :format => [:json] in config/initializers/wrap_parameters.rb is used when parsing posted mentioned parameters (so you can either send json with or without a root element)

What if I cannot trust the (external) client in passing the right header? In other words, I want to have my application behave as if the client always passes the 'Content-type: application/json' header, even if the client actually does not?

like image 445
Pascal Van Hecke Avatar asked Oct 16 '12 13:10

Pascal Van Hecke


1 Answers

You can set the type within an action using

request.format = :json

I tested it using

class ExampleController < ApplicationController

  def always_accept_json
    request.format = :json
    respond_to do |format|
      format.json { raise "HEY" }
      format.html 
    end
  end
end

Which you can do anywhere within Any ActionController i.e. if you wanted at the top level making all request appear to your application as content_type application/json just make it a filter on application_controller.rb that sets request.format

like image 162
Adam Avatar answered Sep 28 '22 08:09

Adam