Skip to content

Instantly share code, notes, and snippets.

@iconara
Last active August 29, 2015 13:56
Show Gist options
  • Save iconara/9072544 to your computer and use it in GitHub Desktop.
Save iconara/9072544 to your computer and use it in GitHub Desktop.
Bypass Grape and Rack::Response's response materialization
require 'grape'
class ResponseHijack
BODY_KEY = 'response_hijack.body'.freeze
CONTENT_TYPE_KEY = 'response_hijack.content_type'.freeze
def initialize(app)
@app = app
end
def call(env)
response = @app.call(env)
if (body = env[BODY_KEY])
content_type = env[CONTENT_TYPE_KEY]
response[1].delete('Content-Length')
response[1]['Content-Type'] = content_type if content_type
response[2] = body
end
response
end
end
class App < Grape::API
format :json
version 'v1', using: :path
namespace do
use ResponseHijack
get do
env[ResponseHijack::BODY_KEY] = ['foo', 'bar']
env[ResponseHijack::CONTENT_TYPE_KEY] = 'text/plain'
nil
end
end
end
run App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment