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.

Defined Under Namespace

Classes: Closed

Instance Method Summary collapse

Methods inherited from Readable

#each, #finish, #join, #length

Constructor Details

#initializeWritable



33
34
35
36
37
38
39
40
41
42
# File 'lib/async/http/body/writable.rb', line 33

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

Instance Method Details

#close(error = nil) ⇒ Object

Stop generating output; cause the next call to write to fail with the given error.



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

def close(error = nil)
  unless @closed
    @queue.enqueue(nil)
    
    @closed = true
    @error = error
  end
  
  super
end

#empty?Boolean

Has the producer called #finish and has the reader consumed the nil token?



57
58
59
# File 'lib/async/http/body/writable.rb', line 57

def empty?
  @finished
end

#inspectObject



88
89
90
# File 'lib/async/http/body/writable.rb', line 88

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

#readObject

Read the next available chunk.



62
63
64
65
66
67
68
69
70
# File 'lib/async/http/body/writable.rb', line 62

def read
  return if @finished
  
  unless chunk = @queue.dequeue
    @finished = true
  end
  
  return chunk
end

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

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



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/async/http/body/writable.rb', line 73

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