From c7dfca86cf9f7e204d2a41700259ced13b336126 Mon Sep 17 00:00:00 2001 From: Ryan Tomayko Date: Tue, 3 Feb 2009 16:50:22 -0800 Subject: [PATCH] Calculate Content-Length using #bytesize instead of #length String#length returns the number of characters in Ruby 1.9. We want the number of bytes. I implemented this by aliasing String#bytesize to String#length when #bytesize is not defined. This seems like a harmless core extension since #bytesize didn't exist prior to 1.8.7. --- lib/sinatra/base.rb | 12 ++++++++---- test/response_test.rb | 9 +++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 1bd24118..52e5f615 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -44,7 +44,7 @@ module Sinatra body = [body] if body.respond_to? :to_str if header["Content-Length"].nil? && body.respond_to?(:to_ary) header["Content-Length"] = body.to_ary. - inject(0) { |len, part| len + part.length }.to_s + inject(0) { |len, part| len + part.bytesize }.to_s end [status.to_i, header.to_hash, body] end @@ -950,8 +950,12 @@ module Sinatra end end -# Define String#each under 1.9 for Rack compatibility. This should be -# removed once Rack is fully 1.9 compatible. class String - alias_method :each, :each_line unless ''.respond_to? :each + # Define String#each under 1.9 for Rack compatibility. This should be + # removed once Rack is fully 1.9 compatible. + alias_method :each, :each_line unless ''.respond_to? :each + + # Define String#bytesize as an alias to String#length for Ruby 1.8.6 and + # earlier. + alias_method :bytesize, :length unless ''.respond_to? :bytesize end diff --git a/test/response_test.rb b/test/response_test.rb index 829bb3b3..5368ef0e 100644 --- a/test/response_test.rb +++ b/test/response_test.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + require File.dirname(__FILE__) + '/helper' describe 'Sinatra::Response' do @@ -30,4 +32,11 @@ describe 'Sinatra::Response' do assert_equal [status_code, {}, []], @response.finish end end + + it 'Calculates the Content-Length using the bytesize of the body' do + @response.body = ['Hello', 'World!', '✈'] + status, headers, body = @response.finish + assert_equal '14', headers['Content-Length'] + assert_equal @response.body, body + end end