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.



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

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.



64
65
66
67
# File 'lib/roda/plugins/streaming.rb', line 64

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

#closeObject

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



71
72
73
74
75
# File 'lib/roda/plugins/streaming.rb', line 71

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

#closed?Boolean

Whether the connection has already been closed.

Returns:

  • (Boolean)


78
79
80
# File 'lib/roda/plugins/streaming.rb', line 78

def closed?
  @closed
end

#each(&out) ⇒ Object

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



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

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.



57
58
59
60
61
# File 'lib/roda/plugins/streaming.rb', line 57

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