Support custom response formats (example for messagepack)
Clone this wiki locally
Support custom response formats (example for MessagePack)
We are experimenting with MessagePack, a high-performance schemaless binary encoding as an optional additional response format to our JSON APIs. Some of the responses we send are quite large, and MessagePack is about 50% faster than the ruby json libraries at encoding them.
MessagePack responses to our acts_as_api-based web service was easy.
First, you must tell
acts_as_api that it should accept an additional api format. You can do this as follows:
ActsAsApi::Config.accepted_api_formats << :mpac
Then, you must add MessagePack as a rails renderer. This will do the trick:
ActionController::Renderers.add :mpac do |object, options| self.content_type ||= 'application/messagepack' self.response_body = MessagePack.pack(object) end
Finally, because MessagePack doesn't come with the ability to serialize a
TimeWithZone, you need to monkey patch it in:
module ActiveSupport class TimeWithZone def to_msgpack(out='') self.to_s.to_msgpack(out) end end end
I put all three of these in
config/initializers/messagepack.rb and it did the trick.