Module: FormData

Defined in:
lib/form_data.rb,
lib/form_data/file.rb,
lib/form_data/version.rb,
lib/form_data/multipart.rb,
lib/form_data/urlencoded.rb,
lib/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

Classes: Error, File, Multipart, Urlencoded

Constant Summary collapse

CRLF =

CRLF

"\r\n".freeze
VERSION =

FormData version

"0.1.0"

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:


40
41
42
43
44
45
# File 'lib/form_data.rb', line 40

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.


52
53
54
55
56
57
58
59
# File 'lib/form_data.rb', line 52

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 fail Error, "#{obj.inspect} is neither Hash nor responds to :to_h"
  end
end