Last active
August 29, 2015 13:56
-
-
Save iconara/9072544 to your computer and use it in GitHub Desktop.
Bypass Grape and Rack::Response's response materialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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