Module: HTTP::FormData

Defined in:
lib/http/form_data.rb,
lib/http/form_data/file.rb,
lib/http/form_data/part.rb,
lib/http/form_data/version.rb,
lib/http/form_data/readable.rb,
lib/http/form_data/multipart.rb,
lib/http/form_data/urlencoded.rb,
lib/http/form_data/composite_io.rb,
lib/http/form_data/multipart/param.rb

Overview

Utility-belt to build form data request bodies. Provides support for application/x-www-form-urlencoded and multipart/form-data types.

Examples:

Usage


form = FormData.create({
  :username     => "ixti",
  :avatar_file  => FormData::File.new("/home/ixti/avatar.png")
})

# Assuming socket is an open socket to some HTTP server
socket << "POST /some-url HTTP/1.1\r\n"
socket << "Host: example.com\r\n"
socket << "Content-Type: #{form.content_type}\r\n"
socket << "Content-Length: #{form.content_length}\r\n"
socket << "\r\n"
socket << form.to_s

Defined Under Namespace

Modules: Readable Classes: CompositeIO, Error, File, Multipart, Part, Urlencoded

Constant Summary collapse

CRLF =

CRLF

"\r\n"
VERSION =

Gem version.

"2.1.1"

Class Method Summary collapse

Class Method Details

.create(data) ⇒ Multipart, Urlencoded

FormData factory. Automatically selects best type depending on given data Hash.

Parameters:

  • data (#to_h, Hash)

Returns:



44
45
46
47
48
49
# File 'lib/http/form_data.rb', line 44

def create(data)
  data  = ensure_hash data
  klass = multipart?(data) ? Multipart : Urlencoded

  klass.new data
end

.ensure_hash(obj) ⇒ Hash

Note:

Internal usage helper, to workaround lack of #to_h on Ruby < 2.1

Coerce obj to Hash.

Returns:

  • (Hash)

Raises:

  • (Error)

    obj can't be coerced.



56
57
58
59
60
61
62
63
# File 'lib/http/form_data.rb', line 56

def ensure_hash(obj)
  case
  when obj.nil?               then {}
  when obj.is_a?(Hash)        then obj
  when obj.respond_to?(:to_h) then obj.to_h
  else raise Error, "#{obj.inspect} is neither Hash nor responds to :to_h"
  end
end