Skip to content

Commit 54046ac

Browse files
committed
Implement parsing msgpack parameter
1 parent 11216e2 commit 54046ac

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

lib/msgpack_rails.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ class Rails < ::Rails::Engine
4646
self.response_body = data.is_a?(String) ? data : data.to_msgpack(options)
4747
end
4848
end
49+
50+
parameter_parser = ->(raw_data) {
51+
data = ActiveSupport::MessagePack.decode(raw_data)
52+
data.is_a?(Hash) ? data : { _msgpack: data }
53+
}
54+
if ::Rails::VERSION::MAJOR >= 5
55+
ActionDispatch::Request.parameter_parsers[Mime[:msgpack].symbol] = parameter_parser
56+
else
57+
ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime[:msgpack]] = parameter_parser
58+
end
4959
end
5060
end
5161
end

test/msgpack_rails/fake_app.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ class FakeApp < Rails::Application
1111
Rails.backtrace_cleaner.remove_silencers!
1212
Rails.application.initialize!
1313

14+
FakeApp.routes.draw do
15+
post ":controller/:action"
16+
end
17+
1418
class ApplicationController < ActionController::Base
1519
end
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
require_relative "../test_helper"
2+
3+
class ParsingParameterController < ApplicationController
4+
def msgpack2json
5+
render json: params[:contact]
6+
end
7+
end
8+
9+
class ParsingParameterTest < ActionDispatch::IntegrationTest
10+
def test_parsing_msgpack_request
11+
contact = Contact.new
12+
contact.name = 'Konata Izumi'
13+
contact.age = 16
14+
contact.created_at = Time.utc(2006, 8, 1)
15+
contact.awesome = true
16+
contact.preferences = { 'shows' => 'anime' }
17+
18+
data = { :contact => contact }.to_msgpack
19+
20+
if ::Rails::VERSION::MAJOR >= 5
21+
post "/parsing_parameter/msgpack2json.json",
22+
params: data,
23+
headers: { "Content-Type" => "application/msgpack" }
24+
else
25+
post "/parsing_parameter/msgpack2json.json",
26+
data,
27+
{ "Content-Type" => "application/msgpack" }
28+
end
29+
30+
assert_response :success
31+
32+
json = ActiveSupport::JSON.decode(response.body)
33+
assert_equal contact.name, json['name']
34+
assert_equal contact.age, json['age']
35+
assert_equal contact.created_at, json['created_at'].to_time
36+
assert_equal contact.awesome, json['awesome']
37+
assert_equal(contact.preferences, json['preferences'])
38+
end
39+
end

0 commit comments

Comments
 (0)