Skip to content

Commit b90875e

Browse files
author
David Heinemeier Hansson
authored
Add ActionController::Live::Buffer#writeln the write a line to the stream with a newline included (rails#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
1 parent 4449e83 commit b90875e

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

actionpack/CHANGELOG.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,20 @@
22

33
```ruby
44
send_stream(filename: "subscribers.csv") do |stream|
5-
stream.write "email_address,updated_at\n"
5+
stream.writeln "email_address,updated_at"
66

77
@subscribers.find_each do |subscriber|
8-
stream.write "#{subscriber.email_address},#{subscriber.updated_at}\n"
8+
stream.writeln [ subscriber.email_address, subscriber.updated_at ].join(",")
99
end
1010
end
1111
```
1212

1313
*DHH*
1414

15+
* Add `ActionController::Live::Buffer#writeln` to write a line to the stream with a newline included.
16+
17+
*DHH*
18+
1519
* `ActionDispatch::Request#content_type` now returned Content-Type header as it is.
1620

1721
Previously, `ActionDispatch::Request#content_type` returned value does NOT contain charset part.

actionpack/lib/action_controller/metal/live.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,11 @@ def write(string)
163163
end
164164
end
165165

166+
# Same as +write+ but automatically include a newline at the end of the string.
167+
def writeln(string)
168+
write string.end_with?("\n") ? string : "#{string}\n"
169+
end
170+
166171
# Write a 'close' event to the buffer; the producer/writing thread
167172
# uses this to notify us that it's finished supplying content.
168173
#

actionpack/test/controller/live_stream_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ def render_text
131131
render plain: "zomg"
132132
end
133133

134+
def write_lines
135+
response.stream.writeln "hello\n"
136+
response.stream.writeln "world"
137+
response.stream.close
138+
end
139+
134140
def default_header
135141
response.stream.write "<html><body>hi</body></html>"
136142
response.stream.close
@@ -312,6 +318,11 @@ def test_write_to_stream
312318
assert_equal "text/event-stream", @response.headers["Content-Type"]
313319
end
314320

321+
def test_write_lines_to_stream
322+
get :write_lines
323+
assert_equal "hello\nworld\n", @response.body
324+
end
325+
315326
def test_send_stream
316327
get :basic_send_stream
317328
assert_equal "name,age\ndavid,41", @response.body

0 commit comments

Comments
 (0)