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.

"3.0.0"

Class Method Summary collapse

Class Method Details

.create(data, encoder: nil) ⇒ Multipart, Urlencoded

Selects encoder type based on given data

Examples:

FormData.create({ username: "ixti" })

Parameters:

  • data (Enumerable, Hash, #to_h)

Returns:



47
48
49
50
51
52
53
54
55
# File 'lib/http/form_data.rb', line 47

def create(data, encoder: nil)
  data = ensure_data data

  if multipart?(data)
    Multipart.new(data)
  else
    Urlencoded.new(data, encoder: encoder)
  end
end

.ensure_data(obj) ⇒ Enumerable

Coerces obj to an Enumerable of key-value pairs

Examples:

FormData.ensure_data([[:foo, :bar]]) # => [[:foo, :bar]]

Returns:

  • (Enumerable)

Raises:

  • (Error)

    obj can’t be coerced



80
81
82
83
84
85
86
# File 'lib/http/form_data.rb', line 80

def ensure_data(obj)
  if    obj.nil?                  then []
  elsif obj.is_a?(Enumerable)     then obj
  elsif obj.respond_to?(:to_h)    then obj.to_h
  else raise Error, "#{obj.inspect} is neither Enumerable nor responds to :to_h"
  end
end

.ensure_hash(obj) ⇒ Hash

Coerces obj to Hash

Examples:

FormData.ensure_hash({ foo: :bar }) # => { foo: :bar }

Returns:

  • (Hash)

Raises:

  • (Error)

    obj can’t be coerced



65
66
67
68
69
70
# File 'lib/http/form_data.rb', line 65

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