Class: Async::HTTP::Body::Writable

Inherits:
Readable
  • Object
show all
Defined in:
lib/async/http/body/writable.rb

Overview

A dynamic body which you can write to and read from.

Instance Method Summary collapse

Methods inherited from Readable

#close, #each, #join, #length

Constructor Details

#initializeWritable

Returns a new instance of Writable.



30
31
32
33
34
35
36
37
# File 'lib/async/http/body/writable.rb', line 30

def initialize
  @queue = Async::Queue.new
  
  @count = 0
  
  @finished = false
  @stopped = nil
end

Instance Method Details

#empty?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/async/http/body/writable.rb', line 39

def empty?
  @finished
end

#finishObject

Signal that output has finished.



81
82
83
# File 'lib/async/http/body/writable.rb', line 81

def finish
  @queue.enqueue(nil)
end

#inspectObject



85
86
87
# File 'lib/async/http/body/writable.rb', line 85

def inspect
  "\#<#{self.class} #{@count} chunks written#{@finished ? ', finished' : ''}>"
end

#readObject

Read the next available chunk.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/async/http/body/writable.rb', line 44

def read
  # I'm not sure if this is a good idea (*).
  # if @stopped
  #  raise @stopped
  # end
  
  return if @finished
  
  unless chunk = @queue.dequeue
    @finished = true
  end
  
  return chunk
end

#stop(error) ⇒ Object

Cause the next call to write to fail with the given error.



60
61
62
# File 'lib/async/http/body/writable.rb', line 60

def stop(error)
  @stopped = error
end

#write(chunk) ⇒ Object Also known as: <<

Write a single chunk to the body. Signal completion by calling ‘#finish`.



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/async/http/body/writable.rb', line 65

def write(chunk)
  # If the reader breaks, the writer will break.
  # The inverse of this is less obvious (*)
  if @stopped
    raise @stopped
  end
  
  # TODO should this yield if the queue is full?
  
  @count += 1
  @queue.enqueue(chunk)
end