Class: HTTPX::Request::Body

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers, options) ⇒ Body

Returns a new instance of Body.



111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/httpx/request.rb', line 111

def initialize(headers, options)
  @headers = headers
  @body = if options.body
    Transcoder.registry("body").encode(options.body)
  elsif options.form
    Transcoder.registry("form").encode(options.form)
  elsif options.json
    Transcoder.registry("json").encode(options.json)
  end
  return if @body.nil?
  @headers["content-type"] ||= @body.content_type
  @headers["content-length"] = @body.bytesize unless unbounded_body?
end

Class Method Details

.new(options) ⇒ Object



105
106
107
108
# File 'lib/httpx/request.rb', line 105

def new(*, options)
  return options.body if options.body.is_a?(self)
  super
end

Instance Method Details

#bytesizeObject



144
145
146
147
148
149
150
151
152
153
# File 'lib/httpx/request.rb', line 144

def bytesize
  return 0 if @body.nil?
  if @body.respond_to?(:bytesize)
    @body.bytesize
  elsif @body.respond_to?(:size)
    @body.size
  else
    raise Error, "cannot determine size of body: #{@body.inspect}"
  end
end

#chunk!Object



169
170
171
# File 'lib/httpx/request.rb', line 169

def chunk!
  @headers.add("transfer-encoding", "chunked")
end

#chunked?Boolean

Returns:

  • (Boolean)


165
166
167
# File 'lib/httpx/request.rb', line 165

def chunked?
  @headers["transfer-encoding"] == "chunked"
end

#each(&block) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/httpx/request.rb', line 125

def each(&block)
  return enum_for(__method__) unless block_given?
  return if @body.nil?
  body = stream(@body)
  if body.respond_to?(:read)
    ::IO.copy_stream(body, ProcIO.new(block))
  elsif body.respond_to?(:each)
    body.each(&block)
  else
    block[body.to_s]
  end
end

#empty?Boolean

Returns:

  • (Boolean)


138
139
140
141
142
# File 'lib/httpx/request.rb', line 138

def empty?
  return true if @body.nil?
  return false if chunked?
  bytesize.zero?
end

#stream(body) ⇒ Object



155
156
157
158
159
# File 'lib/httpx/request.rb', line 155

def stream(body)
  encoded = body
  encoded = Transcoder.registry("chunker").encode(body) if chunked?
  encoded
end

#unbounded_body?Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/httpx/request.rb', line 161

def unbounded_body?
  chunked? || @body.bytesize == Float::INFINITY
end