Skip to content

Commit

Permalink
Add ActionController::Live::Buffer#writeln the write a line to the st…
Browse files Browse the repository at this point in the history
…ream 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
  • Loading branch information
dhh committed Feb 20, 2021
1 parent 4449e83 commit b90875e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions actionpack/CHANGELOG.md
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions actionpack/lib/action_controller/metal/live.rb
Expand Up @@ -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.
#
Expand Down
11 changes: 11 additions & 0 deletions actionpack/test/controller/live_stream_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit b90875e

Please sign in to comment.