Automatically encode rack output using JSON when Content-Type is application / json

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 is actually set with a before filter
    # included only for clarity
    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?

+3
source share
1

, : Rack , , each, . .

, , , .

if json_response?
  @body = [@body.to_json]
  @headers["Content-Length"] = @body[0].size.to_s
end
+4

Source: https://habr.com/ru/post/1758384/


All Articles