Parsing MessagePack in Rails > 5.1

This is an update to earlier post where MessagePack body was parsed to controller params using Rack middleware. That approach relied on ActionDispatch::ParamsParser which got deprecated in 5.1 while custom mime type params parsing got simpler.

For parsing MessagePack request body as controller parameters with Rails > 5 you’ll need msgpack gem and then you are able to provide custom mime types and parsers as ActionDispatch::Request.parameter_parsers array.

  1. Include gem 'msgpack' in your Gemfile
  2. Register mime type for Rails
  3. Configure parameter wrapping similar to json behavior or as you see fit in your case in config/initializers/wrap_parameters.rb
  4. Configure custom parser in eg. config/initializers/parse_msgpack.rb

MessagePack parser configuration

Include following in config/initializers/mime_types.rb to register msgpack mime type.

Mime::Type.register "application/msgpack", :msgpack

Include following in Rails initializer file. For example config/initializers/parse_msgpack.rb.

# Create parameter parser for MessagePack
msgpack_parser = -> (raw_post) { MessagePack.unpack(raw_post) || {} }
ActionDispatch::Request.parameter_parsers.merge! msgpack: msgpack_parser

See this example project for more details about configuration and example on writing MessagePack related controller tests.