Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: ActionDispatch::Request.parameter_parsers for multipart/form-data

In my rails API, I have added an initialiser that will change the keys of the JSON input from snake-case to underscore-separated. Like so:

ActionDispatch::Request.parameter_parsers[:json] = -> (raw_post) {
    data = ActiveSupport::JSON.decode(raw_post)
    data = {:_json => data} unless data.is_a?(Hash)

    data.deep_transform_keys!(&:underscore)
}

Now, certain APIs will be passed with the header: content-type: multipart/form-data instead of application/json

I want to do the same for such APIs. That is add an initialiser that will convert the case of the keys in the parameters.

I tried ActionDispatch::Request.parameter_parsers[:form_data] but it dit not work.

How can I achieve this?

like image 272
mridula Avatar asked Aug 14 '26 14:08

mridula


1 Answers

When you look at the DEFAULT_PARSERS, it uses the Mime class, so whatever we end up using will likely need to be recognizable by the Mime class. So we can check Mime::Types to see what's available.

On that page, we see that content-type: multipart/form-data is mapped to :multipart_form. Indeed, while using

ActionDispatch::Request.parameter_parsers[:multipart_form] = -> (raw_post) {
  raise "Parsing Parameters: #{raw_post}"
}

and then submitting a form with a file field, I can trigger the error.

like image 186
Simple Lime Avatar answered Aug 17 '26 04:08

Simple Lime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!