Class: Itsi::HttpResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/itsi/http_response.rb

Instance Method Summary collapse

Instance Method Details

#respond(_body = nil, _status = 200, _header = nil, status: _status, headers: _header, body: _body, hijack: false) ⇒ Object



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
# File 'lib/itsi/http_response.rb', line 9

def respond(
  _body = nil, _status = 200, _header = nil, # rubocop:disable Lint/UnderscorePrefixedVariableName
  status: _status, headers: _header, body: _body,
  hijack: false
)
  self.status = status.is_a?(Symbol) ? HTTP_STATUS_NAME_TO_CODE_MAP.fetch(status) : status.to_i

  body = body.to_s unless body.is_a?(String)

  if headers
    headers.each do |key, value|
      if value.is_a?(Array)
        value.each { |v| add_header(key, v) }
      else
        add_header(key, value)
      end
    end
  end

  if body
    # Common case. Write a single string body.
    send_and_close(body)
  elsif block_given?

    # If you call respond with a block, you get a handle to a stream that you can write to.
    yield self

    # If you hijack the connection, you are responsible for closing it.
    # Otherwise, the response will be closed automatically.
    close unless hijack
  else
    close
  end
end