Class: Philiprehberger::Multipart::Part

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/multipart/part.rb

Overview

Represents a single part in a multipart/form-data body

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value, filename: nil, content_type: nil) ⇒ Part

Returns a new instance of Part.

Parameters:

  • name (Symbol)

    the field name

  • value (String)

    the part value

  • filename (String, nil) (defaults to: nil)

    the original filename

  • content_type (String, nil) (defaults to: nil)

    the MIME content type



23
24
25
26
27
28
# File 'lib/philiprehberger/multipart/part.rb', line 23

def initialize(name, value, filename: nil, content_type: nil)
  @name = name
  @value = value
  @filename = filename
  @content_type = content_type
end

Instance Attribute Details

#content_typeString?

Returns the content type.

Returns:

  • (String, nil)

    the content type



17
18
19
# File 'lib/philiprehberger/multipart/part.rb', line 17

def content_type
  @content_type
end

#filenameString?

Returns the original filename.

Returns:

  • (String, nil)

    the original filename



14
15
16
# File 'lib/philiprehberger/multipart/part.rb', line 14

def filename
  @filename
end

#nameSymbol (readonly)

Returns the field name.

Returns:

  • (Symbol)

    the field name



8
9
10
# File 'lib/philiprehberger/multipart/part.rb', line 8

def name
  @name
end

#valueString

Returns the part value / body content.

Returns:

  • (String)

    the part value / body content



11
12
13
# File 'lib/philiprehberger/multipart/part.rb', line 11

def value
  @value
end

Instance Method Details

#bodyString

Alias for value — the body content of this part

Returns:

  • (String)


33
34
35
# File 'lib/philiprehberger/multipart/part.rb', line 33

def body
  @value
end

#file?Boolean

Whether this part represents a file upload

Returns:

  • (Boolean)


40
41
42
# File 'lib/philiprehberger/multipart/part.rb', line 40

def file?
  !@filename.nil?
end

#to_s(boundary) ⇒ String

Render this part as a multipart body segment

Parameters:

  • boundary (String)

    the multipart boundary

Returns:

  • (String)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/philiprehberger/multipart/part.rb', line 48

def to_s(boundary)
  lines = []
  lines << "--#{boundary}\r\n"

  if file?
    lines << "Content-Disposition: form-data; name=\"#{@name}\"; filename=\"#{@filename}\"\r\n"
    lines << "Content-Type: #{@content_type || 'application/octet-stream'}\r\n"
  else
    lines << "Content-Disposition: form-data; name=\"#{@name}\"\r\n"
  end

  lines << "\r\n"
  lines << @value
  lines << "\r\n"
  lines.join
end