私はモジュール式の Sinatra アプリを持っており、コンテンツ タイプが指示するときに出力を JSON としてエンコードしたいと考えています。現時点では、ルートで手動で行っています:
get 'someroute' do
# content-type is actually set with a before filter
# included only for clarity
content_type 'application/json', :charset => 'utf-8'
# .. #
{:success=>true}.to_json
end
私はそれが次のように見えることを望みます:
get 'someroute' do
content_type 'application/json', :charset => 'utf-8'
# .. #
{:success=>true}
end
また、適切なコンテンツ タイプが検出された場合は、Rack ミドルウェアを使用してエンコードを行いたいと考えています。
私は以下を機能させようとしましたが、役に立ちませんでした(コンテンツの長さが壊れます-JSONでエンコードされたコンテンツではなく、元のコンテンツのコンテンツの長さを返します):
require 'init'
module Rack
class JSON
def initialize app
@app = app
end
def call env
@status, @headers, @body = @app.call env
if json_response?
@body = @body.to_json
end
[@status, @headers, @body]
end
def json_response?
@headers['Content-Type'] == 'application/json'
end
end
end
use Rack::JSON
MyApp.set :run, false
MyApp.set :environment, ENV['RACK_ENV'].to_sym
run MyApp
私を軌道に乗せるための指針はありますか?