Class: IntervalResponse::RackBodyWrapper
- Inherits:
-
Object
- Object
- IntervalResponse::RackBodyWrapper
- Defined in:
- lib/interval_response/rack_body_wrapper.rb
Overview
The Rack body wrapper is intended to be returned as the third element of the Rack response triplet. It supports the #each method and will call to the IntervalResponse object given to it at instantiation, filling up a pre-allocated String object with the bytes to be served out. The String object will then be repeatedly yielded to the Rack webserver with the response data. Since Ruby strings are mutable, the String object will be sized to a certain capacity and reused across calls to save allocations.
Constant Summary collapse
- CHUNK_SIZE =
Default size of the chunk (String buffer) which is going to be yielded to the caller of the ‘each` method. Set toroughly one TCP kernel buffer
65 * 1024
Instance Method Summary collapse
- #each ⇒ Object
-
#initialize(with_interval_response, chunk_size:) ⇒ RackBodyWrapper
constructor
A new instance of RackBodyWrapper.
Constructor Details
#initialize(with_interval_response, chunk_size:) ⇒ RackBodyWrapper
Returns a new instance of RackBodyWrapper.
15 16 17 18 |
# File 'lib/interval_response/rack_body_wrapper.rb', line 15 def initialize(with_interval_response, chunk_size:) @chunk_size = chunk_size @interval_response = with_interval_response end |
Instance Method Details
#each ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/interval_response/rack_body_wrapper.rb', line 20 def each buf = String.new(capacity: @chunk_size) @interval_response.each do |segment, range_in_segment| case segment when IntervalResponse::LazyFile segment.with do |file_handle| with_each_chunk(range_in_segment) do |offset, read_n| file_handle.seek(offset, IO::SEEK_SET) yield file_handle.read(read_n, buf) end end when String with_each_chunk(range_in_segment) do |offset, read_n| yield segment.slice(offset, read_n) end when IO, Tempfile with_each_chunk(range_in_segment) do |offset, read_n| segment.seek(offset, IO::SEEK_SET) yield segment.read(read_n, buf) end else raise TypeError, "RackBodyWrapper only supports IOs or Strings" end end ensure buf.clear end |