Class: FormData::Multipart::Param

Inherits:
Object
  • Object
show all
Defined in:
lib/form_data/multipart/param.rb

Overview

Utility class to represent multi-part chunks

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value) ⇒ Param

Returns a new instance of Param

Parameters:


9
10
11
12
13
14
15
16
17
18
19
# File 'lib/form_data/multipart/param.rb', line 9

def initialize(name, value)
  @name, @value = name.to_s, value

  @header = "Content-Disposition: form-data; name=#{@name.inspect}"

  return unless file?

  @header << "; filename=#{value.filename.inspect}"
  @header << CRLF
  @header << "Content-Type: #{value.mime_type}"
end

Class Method Details

.coerce(data) ⇒ Array<FormData::MultiPart::Param>

Flattens given data Hash into an array of Param's. Nested array are unwinded. Behavior is pretty similar to URL.encode_www_form.

Parameters:

  • data (Hash)

Returns:

  • (Array<FormData::MultiPart::Param>)

59
60
61
62
63
64
65
66
67
68
69
# File 'lib/form_data/multipart/param.rb', line 59

def self.coerce(data)
  params = []

  data.each do |name, values|
    Array(values).each do |value|
      params << new(name, value)
    end
  end

  params
end

Instance Method Details

#sizeFixnum

Calculates size of a part (headers + body).

Returns:

  • (Fixnum)

44
45
46
47
48
49
50
51
52
# File 'lib/form_data/multipart/param.rb', line 44

def size
  size = @header.bytesize + (CRLF.bytesize * 2)

  if file?
    size + @value.size
  else
    size + @value.to_s.bytesize
  end
end

#to_sString

Returns body part with headers and data.

Examples:

With File value


Content-Disposition: form-data; name="avatar"; filename="avatar.png"
Content-Type: application/octet-stream

...data of avatar.png...

With non-File value


Content-Disposition: form-data; name="username"

ixti

Returns:

  • (String)

37
38
39
# File 'lib/form_data/multipart/param.rb', line 37

def to_s
  "#{@header}#{CRLF * 2}#{@value}"
end