Class: HTTP::Request::Body

Inherits:
Object
  • Object
show all
Defined in:
lib/http/request/body.rb

Overview

Represents an HTTP request body with streaming support

Direct Known Subclasses

Features::AutoDeflate::CompressedBody

Defined Under Namespace

Classes: ProcIO

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ HTTP::Request::Body

Initialize a new request body

Examples:

Body.new("hello world")


23
24
25
26
27
# File 'lib/http/request/body.rb', line 23

def initialize(source)
  @source = source

  validate_source_type!
end

Instance Attribute Details

#sourceString, ... (readonly)

The source data for this body

Examples:

body.source # => "hello world"

Returns:

  • (String, Enumerable, IO, nil)


14
15
16
# File 'lib/http/request/body.rb', line 14

def source
  @source
end

Instance Method Details

#==(other) ⇒ Boolean

Check equality based on source

Examples:

body == other_body

Returns:

  • (Boolean)


109
110
111
# File 'lib/http/request/body.rb', line 109

def ==(other)
  other.is_a?(self.class) && source == other.source
end

#each {|| ... } ⇒ self

Yields chunks of content to be streamed

Examples:

body.each { |chunk| socket.write(chunk) }

Yield Parameters:

  • (String)

Returns:

  • (self)


89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/http/request/body.rb', line 89

def each(&block)
  if @source.is_a?(String)
    yield @source
  elsif @source.respond_to?(:read)
    IO.copy_stream(@source, ProcIO.new(block))
    rewind(@source)
  elsif @source
    @source.each(&block)
  end

  self
end

#empty?Boolean

Whether the body is empty

Examples:

body.empty? # => true

Returns:

  • (Boolean)


36
37
38
# File 'lib/http/request/body.rb', line 36

def empty?
  @source.nil?
end

#loggable?Boolean

Whether the body content can be accessed for logging

Returns true for String sources (the content can be inspected). Returns false for IO streams and Enumerables (which cannot be read without consuming them), and for nil bodies.

The logging feature checks the string encoding separately to decide whether to log the content as text or format it as binary.

Examples:

body.loggable? # => true

Returns:

  • (Boolean)


54
55
56
# File 'lib/http/request/body.rb', line 54

def loggable?
  @source.is_a?(String)
end

#sizeInteger

Returns size for the “Content-Length” header

Examples:

body.size

Returns:

  • (Integer)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/http/request/body.rb', line 65

def size
  if @source.is_a?(String)
    @source.bytesize
  elsif @source.respond_to?(:read)
    raise RequestError, "IO object must respond to #size" unless @source.respond_to?(:size)

    @source.size
  elsif @source.nil?
    0
  else
    raise RequestError,
          "cannot determine size of body: #{@source.inspect}; " \
          "set the Content-Length header explicitly or use chunked Transfer-Encoding"
  end
end