File tree 2 files changed +27
-10
lines changed
2 files changed +27
-10
lines changed Original file line number Diff line number Diff line change @@ -3168,7 +3168,7 @@ end
3168
3168
3169
3169
Use `body false` to return `204 No Content` without any data or content-type.
3170
3170
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` .
3172
3172
3173
3173
```ruby
3174
3174
class API < Grape::API
@@ -3178,8 +3178,8 @@ class API < Grape::API
3178
3178
end
3179
3179
```
3180
3180
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.
3183
3183
Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.
3184
3184
3185
3185
```ruby
Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ Upgrading Grape
7
7
8
8
Previously in 0.16 stream-like objects were deprecated. This release restores their functionality for use-cases other than file streaming.
9
9
10
- For streaming files, simply use file always.
10
+ For streaming files, use ` file ` always.
11
11
12
12
``` ruby
13
13
class API < Grape ::API
@@ -17,22 +17,39 @@ class API < Grape::API
17
17
end
18
18
```
19
19
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.
22
22
23
23
``` ruby
24
- class MyObject
24
+ class MyObject
25
+ attr_accessor :result
26
+
27
+ def initialize (query )
28
+ @result = query
29
+ end
30
+
25
31
def each
26
32
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
29
39
yield ' ]'
30
40
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
31
48
end
32
49
33
50
class API < Grape ::API
34
51
get ' /' do
35
- stream MyObject .new
52
+ stream MyObject .new ( Sprocket .all)
36
53
end
37
54
end
38
55
```
You can’t perform that action at this time.
0 commit comments