LoginSignup
4
4

More than 5 years have passed since last update.

Sinatraのjson_encoderを入れ替える

Posted at

TL;DR

  • Sinatraのjson_encoderを入れ替える
  • :json_encoder => some_encoder で渡せる
  • oj は Sinatra内部で呼ばれるmethodがないので別途作成して食わせる

ref

sample

  • Gemfile
source "https://rubygems.org"

# utilities
gem "rake", '~> 10'
gem "yajl-ruby"
gem "oj"
gem "oj_mimic_json"

# rack-app
gem "thin"
gem "sinatra"
gem "sinatra-contrib"
gem "unicorn"
app.rb
require 'sinatra'
require 'sinatra/json'
require 'yajl'
require 'oj'
require 'oj_mimic_json'
require './oj_encoder.rb'

get '/oj' do
  hash = {}
  hash['key'] = 'hoge'
  hash['key2'] = 'fuga'
  hash['uuid'] = SecureRandom.uuid
  json hash, :json_encoder => OjEncoder.new
end

get '/yajl' do
  hash = {}
  hash[:key] = 'hoge'
  hash[:key2] = 'fuga'
  hash[:uuid] = SecureRandom.uuid
  json hash, :json_encoder => Yajl::Encoder
end

get '/' do
  hash = {}
  hash[:key] = 'hoge'
  hash[:key2] = 'fuga'
  hash[:uuid] = SecureRandom.uuid
  json hash
end
config.ru
require 'rubygems'
require 'sinatra'

require './app.rb'

run Sinatra::Application
oj_encoder.rb
require 'oj'

class OjEncoder

  def initialize
    ::Oj.default_options = {:mode => :compat }
  end

  def encode(value)
    ::Oj.dump(value)
  end

end

4
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
4
4