5
4

More than 5 years have passed since last update.

MsgpackRails で何か値を返すヤツ

Last updated at Posted at 2014-04-28

テストサーバを作る

rails new testapp で適当なRailsプロジェクトを作る

Gemfile に以下の行を追加

gem 'msgpack-rails', :git => 'git://github.com/nzifnab/msgpack-rails.git'

適当なコントローラを用意して以下のようにレスポンスを返すコードを記述

test_controller.rb
class TestController < ApplicationController
  def index
    response_data = {
      :player_info => {
        :name => "hoge",
        :age => 35
      },
      :friends => [10, 20, 30]
    }
    render :text => response_data.to_msgpack, :type => 'application/x-mpac'
  end
end

サーバ起動して、http://localhost:3000/ にアクセスするとMsgPackでパックされたバイナリが返ってくる。

レスポンスをUnpackしてみる

pryなどで、MessagePack.unpack してみて、元の Hash 構造が復元できることを確認。

require 'msgpack'

res = Net::HTTP.get(URI.parse('http://localhost:3000/'))

MessagePack.unpack(res)
=> {"player_info"=>{"name"=>"hoge", "age"=>35}, "friends"=>[10, 20, 30]}

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4