Class: Infrawrench::Upload

Inherits:
Object
  • Object
show all
Defined in:
lib/infrawrench/transport.rb,
sig/infrawrench/sdk.rbs

Overview

A file to send in a multipart/form-data request.

Call sites rarely need this: a plain String of bytes or any IO-like object is accepted wherever a file is expected, and Upload.coerce wraps it. Construct one explicitly only to control the filename or content type the server sees.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content, filename: "file", content_type: "application/octet-stream") ⇒ Upload

Returns a new instance of Upload.

Parameters:

  • (Upload, _Readable, String)
  • filename: (String) (defaults to: "file")
  • content_type: (String) (defaults to: "application/octet-stream")


75
76
77
78
79
# File 'lib/infrawrench/transport.rb', line 75

def initialize(content, filename: "file", content_type: "application/octet-stream")
  @bytes = (content.respond_to?(:read) ? content.read : content.to_s).b
  @filename = filename
  @content_type = content_type
end

Instance Attribute Details

#bytesString (readonly)

Returns The file's bytes.

Returns:

  • (String)

    The file's bytes.



69
70
71
# File 'lib/infrawrench/transport.rb', line 69

def bytes
  @bytes
end

#content_typeString (readonly)

Returns Content-Type sent for the part.

Returns:

  • (String)

    Content-Type sent for the part.



73
74
75
# File 'lib/infrawrench/transport.rb', line 73

def content_type
  @content_type
end

#filenameString (readonly)

Returns Filename sent in the part's Content-Disposition.

Returns:

  • (String)

    Filename sent in the part's Content-Disposition.



71
72
73
# File 'lib/infrawrench/transport.rb', line 71

def filename
  @filename
end

Class Method Details

.coerce(value) ⇒ Upload

Wrap whatever a caller passed for a file field.

A File keeps its basename, because a server that stores the upload under the name it was given should get the name the user actually chose.

Parameters:

Returns:



88
89
90
91
92
93
94
# File 'lib/infrawrench/transport.rb', line 88

def self.coerce(value)
  return value if value.is_a?(Upload)
  return new(value) unless value.respond_to?(:read)

  path = value.respond_to?(:path) ? value.path : nil
  path ? new(value, filename: File.basename(path)) : new(value)
end