I have a modular Sinatra application, and I would like to encode the output as JSON when dictating the type of content. I am currently doing this manually on my routes:
get 'someroute' do
content_type 'application/json', :charset => 'utf-8'
{:success=>true}.to_json
end
I would prefer it to look like this:
get 'someroute' do
content_type 'application/json', :charset => 'utf-8'
{:success=>true}
end
And I would like to use Rack middleware for coding if it detects the appropriate type of content.
I am trying to get the following to work, but to no avail (the length of the content gets borked - returns the length of the contents of the original content, not the encoded JSON content):
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
Any pointers to get me back on track?
source
share