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