mirror of
https://github.com/sinatra/sinatra
synced 2023-03-27 23:18:01 -04:00
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.
This commit is contained in:
parent
b5d4a5e636
commit
c7dfca86cf
2 changed files with 17 additions and 4 deletions
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue