Skip to content

Commit

Permalink
force the resposne format so Rack::ContentLength will work correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
dj2 committed Mar 8, 2011
1 parent 32d10f9 commit 46cafe4
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 2 deletions.
19 changes: 19 additions & 0 deletions examples/valid.rb
@@ -0,0 +1,19 @@
#!/usr/bin/env ruby
$:<< '../lib' << 'lib'

require 'goliath'

class Valid < Goliath::API

# reload code on every request in dev environment
use ::Rack::Reloader, 0 if Goliath.dev?

use Goliath::Rack::Params
use Goliath::Rack::ValidationError

use Goliath::Rack::Validation::RequiredParam, {:key => 'test'}

def response(env)
[200, {}, 'OK']
end
end
1 change: 1 addition & 0 deletions lib/goliath.rb
Expand Up @@ -14,6 +14,7 @@
require 'goliath/headers'
require 'goliath/http_status_codes'

require 'goliath/rack/default_response_format'
require 'goliath/rack/heartbeat'
require 'goliath/rack/params'
require 'goliath/rack/render'
Expand Down
3 changes: 2 additions & 1 deletion lib/goliath/api.rb
Expand Up @@ -20,7 +20,8 @@ class << self
#
# @return [Array] array contains [middleware class, args, block]
def middlewares
@middlewares ||= [[::Rack::ContentLength, nil, nil]]
@middlewares ||= [[::Rack::ContentLength, nil, nil],
[Goliath::Rack::DefaultResponseFormat, nil, nil]]
end

# Specify a middleware to be used by the API
Expand Down
33 changes: 33 additions & 0 deletions lib/goliath/rack/default_response_format.rb
@@ -0,0 +1,33 @@
module Goliath
module Rack
class DefaultResponseFormat
def initialize(app)
@app = app
end

def call(env)
async_cb = env['async.callback']
env['async.callback'] = Proc.new do |status, headers, body|
async_cb.call(post_process(status, headers, body))
end

status, headers, body = @app.call(env)
post_process(status, headers, body)
end

def post_process(status, headers, body)
return [status, headers, body] if body.respond_to?(:to_ary)

new_body = []
if body.respond_to?(:each)
body.each { |chunk| new_body << chunk }
else
new_body << body
end
new_body.collect! { |item| item.to_s }

[status, headers, new_body.flatten]
end
end
end
end
2 changes: 1 addition & 1 deletion lib/goliath/rack/validation_error.rb
Expand Up @@ -35,4 +35,4 @@ def call(env)
end
end
end
end
end
24 changes: 24 additions & 0 deletions spec/integration/valid_spec.rb
@@ -0,0 +1,24 @@
require 'spec_helper'
require File.join(File.dirname(__FILE__), '../../', 'examples/valid')

describe Valid do
include Goliath::TestHelper

let(:err) { Proc.new { fail "API request failed" } }

it 'returns OK with param' do
with_api(Valid) do
get_request({:query => {:test => 'test'}}, err) do |c|
c.response.should == 'OK'
end
end
end

it 'returns error without param' do
with_api(Valid) do
get_request({}, err) do |c|
c.response.should == '[:error, "Test identifier missing"]'
end
end
end
end

0 comments on commit 46cafe4

Please sign in to comment.