Class: Roda::RodaPlugins::Streaming::Stream

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/roda/plugins/streaming.rb

Overview

Class of the response body in case you use #stream.

Instance Method Summary collapse

Constructor Details

#initialize(opts = OPTS, &block) ⇒ Stream

Handle streaming options, see Streaming for details.



51
52
53
54
55
56
# File 'lib/roda/plugins/streaming.rb', line 51

def initialize(opts=OPTS, &block)
  @block = block
  @out = nil
  @callback = opts[:callback]
  @closed = false
end

Instance Method Details

#<<(data) ⇒ Object

Add output to the streaming response body. Returns self.



66
67
68
69
# File 'lib/roda/plugins/streaming.rb', line 66

def <<(data)
  write(data)
  self
end

#closeObject

If not already closed, close the connection, and call any callbacks.



73
74
75
76
77
# File 'lib/roda/plugins/streaming.rb', line 73

def close
  return if closed?
  @closed = true
  @callback.call if @callback
end

#closed?Boolean

Whether the connection has already been closed.

Returns:

  • (Boolean)


80
81
82
# File 'lib/roda/plugins/streaming.rb', line 80

def closed?
  @closed
end

#each(&out) ⇒ Object

Yield values to the block as they are passed in via #<<.



85
86
87
88
89
90
# File 'lib/roda/plugins/streaming.rb', line 85

def each(&out)
  @out = out
  @block.call(self)
ensure
  close
end

#write(data) ⇒ Object

Add output to the streaming response body. Returns number of bytes written.



59
60
61
62
63
# File 'lib/roda/plugins/streaming.rb', line 59

def write(data)
  data = data.to_s
  @out.call(data)
  data.bytesize
end