lib/grape/middleware/formatter.rb in grape-0.12.0 vs lib/grape/middleware/formatter.rb in grape-0.13.0

- old
+ new

@@ -9,44 +9,60 @@ formatters: {}, parsers: {} } end - def headers - env.dup.inject({}) do |h, (k, v)| - h[k.to_s.downcase[5..-1]] = v if k.to_s.downcase.start_with?('http_') - h - end - end - def before negotiate_content_type read_body_input end def after status, headers, bodies = *@app_response - # allow content-type to be explicitly overwritten - api_format = mime_types[headers[Grape::Http::Headers::CONTENT_TYPE]] || env['api.format'] - formatter = Grape::Formatter::Base.formatter_for api_format, options - begin - bodymap = if bodies.respond_to?(:collect) - bodies.collect do |body| - formatter.call body, env - end - else - bodies - end - rescue Grape::Exceptions::InvalidFormatter => e - throw :error, status: 500, message: e.message + + if bodies.is_a?(Grape::Util::FileResponse) + headers = ensure_content_type(headers) + + response = + Rack::Response.new([], status, headers) do |resp| + resp.body = bodies.file + end + else + # Allow content-type to be explicitly overwritten + api_format = mime_types[headers[Grape::Http::Headers::CONTENT_TYPE]] || env['api.format'] + formatter = Grape::Formatter::Base.formatter_for(api_format, options) + + begin + bodymap = bodies.collect do |body| + formatter.call(body, env) + end + + headers = ensure_content_type(headers) + + response = Rack::Response.new(bodymap, status, headers) + rescue Grape::Exceptions::InvalidFormatter => e + throw :error, status: 500, message: e.message + end end - headers[Grape::Http::Headers::CONTENT_TYPE] = content_type_for(env['api.format']) unless headers[Grape::Http::Headers::CONTENT_TYPE] - Rack::Response.new(bodymap, status, headers) + + response end private + # Set the content type header for the API format if it is not already present. + # + # @param headers [Hash] + # @return [Hash] + def ensure_content_type(headers) + if headers[Grape::Http::Headers::CONTENT_TYPE] + headers + else + headers.merge(Grape::Http::Headers::CONTENT_TYPE => content_type_for(env['api.format'])) + end + end + def request @request ||= Rack::Request.new(env) end # store read input in env['api.request.input'] @@ -131,10 +147,10 @@ end nil end def mime_array - accept = headers[Grape::Http::Headers::ACCEPT] + accept = env[Grape::Http::Headers::HTTP_ACCEPT] return [] unless accept accept_into_mime_and_quality = %r{ ( \w+/[\w+.-]+) # eg application/vnd.example.myformat+xml