aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/client/response.rb
blob: 0756546cd91e1d2b6e177237dba41f8732406451 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
47
48
# -*- frozen-string-literal: true -*-
module Plum
  class Response
    attr_reader :headers

    def initialize
      @body = Queue.new
      @finished = false
      @body_read = false
    end

    def status
      @headers && @headers[":status"]
    end

    def finished?
      @finished
    end

    def each_body(&block)
      raise "Body already read" if @body_read
      @body_read = true
      while chunk = @body.pop
        yield chunk
      end
    end

    def body
      body = String.new
      each_body { |chunk| body << chunk }
      body
    end

    def _headers(raw_headers)
      # response headers should not have duplicates
      @headers = raw_headers.to_h
    end

    def _chunk(chunk)
      @body << chunk
    end

    def _finish
      @finished = true
      @body << nil # @body.close is not implemented in Ruby 2.2
    end
  end
end