Skip to content

Commit 726b59d

Browse files
committed
fixup! un-deprecate stream-like objects
1 parent c7da23b commit 726b59d

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -3168,7 +3168,7 @@ end
31683168
31693169
Use `body false` to return `204 No Content` without any data or content-type.
31703170
3171-
You can also set the response to a file with `file` and it will be streamed using Rack::Chunked.
3171+
You can also set the response to a file with `file` and it will be streamed using `Rack::Chunked`.
31723172
31733173
```ruby
31743174
class API < Grape::API
@@ -3178,8 +3178,8 @@ class API < Grape::API
31783178
end
31793179
```
31803180
3181-
If you want to stream non-file data you use the stream method and a Stream object.
3182-
This is simply an object that responds to each and yields for each chunk to send to the client.
3181+
If you want to stream non-file data you use the stream method and a `Stream` object.
3182+
This is an object that responds to `each` and yields for each chunk to send to the client.
31833183
Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.
31843184
31853185
```ruby

UPGRADING.md

+24-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Upgrading Grape
77

88
Previously in 0.16 stream-like objects were deprecated. This release restores their functionality for use-cases other than file streaming.
99

10-
For streaming files, simply use file always.
10+
For streaming files, use `file` always.
1111

1212
```ruby
1313
class API < Grape::API
@@ -17,22 +17,39 @@ class API < Grape::API
1717
end
1818
```
1919

20-
If you want to stream other kinds of content from a streamer object you may.
21-
An example would be a streamer class that fetches several pages of data from a database and streams the formatted responses back.
20+
Use `stream` to stream other kinds of content. In the following example a streamer class
21+
streams paginated data from a database.
2222

2323
```ruby
24-
class MyObject
24+
class MyObject
25+
attr_accessor :result
26+
27+
def initialize(query)
28+
@result = query
29+
end
30+
2531
def each
2632
yield '['
27-
# maybe do some paginated DB fetches and return each page
28-
yield {}.to_json
33+
# Do paginated DB fetches and return each page formatted
34+
first = false
35+
result.find_in_batches do |records|
36+
yield process_records(records, first)
37+
first = false
38+
end
2939
yield ']'
3040
end
41+
42+
def process_records(records, first)
43+
buffer = +''
44+
buffer << ',' unless first
45+
buffer << records.map(&:to_json).join(',')
46+
buffer
47+
end
3148
end
3249

3350
class API < Grape::API
3451
get '/' do
35-
stream MyObject.new
52+
stream MyObject.new(Sprocket.all)
3653
end
3754
end
3855
```

0 commit comments

Comments
 (0)