Add ActionController::Live::Buffer#writeln the write a line to the stream with a newline included (#41501)

* Add ActionController::Live::Buffer#writeln to write a line to the stream with a newline included

* Don't add newlines to strings that already have them
This commit is contained in:
David Heinemeier Hansson 2021-02-20 10:02:49 +01:00 committed by GitHub
parent 4449e83284
commit b90875ebd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 2 deletions

@ -2,16 +2,20 @@
```ruby
send_stream(filename: "subscribers.csv") do |stream|
stream.write "email_address,updated_at\n"
stream.writeln "email_address,updated_at"
@subscribers.find_each do |subscriber|
stream.write "#{subscriber.email_address},#{subscriber.updated_at}\n"
stream.writeln [ subscriber.email_address, subscriber.updated_at ].join(",")
end
end
```
*DHH*
* Add `ActionController::Live::Buffer#writeln` to write a line to the stream with a newline included.
*DHH*
* `ActionDispatch::Request#content_type` now returned Content-Type header as it is.
Previously, `ActionDispatch::Request#content_type` returned value does NOT contain charset part.

@ -163,6 +163,11 @@ def write(string)
end
end
# Same as +write+ but automatically include a newline at the end of the string.
def writeln(string)
write string.end_with?("\n") ? string : "#{string}\n"
end
# Write a 'close' event to the buffer; the producer/writing thread
# uses this to notify us that it's finished supplying content.
#

@ -131,6 +131,12 @@ def render_text
render plain: "zomg"
end
def write_lines
response.stream.writeln "hello\n"
response.stream.writeln "world"
response.stream.close
end
def default_header
response.stream.write "<html><body>hi</body></html>"
response.stream.close
@ -312,6 +318,11 @@ def test_write_to_stream
assert_equal "text/event-stream", @response.headers["Content-Type"]
end
def test_write_lines_to_stream
get :write_lines
assert_equal "hello\nworld\n", @response.body
end
def test_send_stream
get :basic_send_stream
assert_equal "name,age\ndavid,41", @response.body