Class: HTTP::FormData::File

Inherits:
Part
  • Object
show all
Defined in:
lib/http/form_data/file.rb

Overview

Represents file form param.

Examples:

Usage with StringIO


io = StringIO.new "foo bar baz"
FormData::File.new io, filename: "foobar.txt"

Usage with IO


File.open "/home/ixti/avatar.png" do |io|
  FormData::File.new io
end

Usage with pathname


FormData::File.new "/home/ixti/avatar.png"

Constant Summary collapse

DEFAULT_MIME =

Default MIME type

"application/octet-stream"

Instance Attribute Summary

Attributes inherited from Part

#content_type, #filename

Instance Method Summary collapse

Methods included from Readable

#read, #rewind, #size, #to_s

Constructor Details

#initialize(path_or_io, opts = nil) ⇒ File

Creates a new File from a path or IO object

Examples:

File.new("/path/to/file.txt")

Parameters:

  • path_or_io (String, Pathname, IO)

    Filename or IO instance

  • opts (#to_h) (defaults to: nil)

Options Hash (opts):

  • :content_type (#to_s) — default: DEFAULT_MIME

    Value of Content-Type header

  • :filename (#to_s)

    When path_or_io is a String, Pathname or File, defaults to basename. When path_or_io is a IO, defaults to ‘“stream-object_id”`

See Also:



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

def initialize(path_or_io, opts = nil) # rubocop:disable Lint/MissingSuper
  opts = FormData.ensure_hash(opts)

  @io           = make_io(path_or_io)
  @autoclose    = path_or_io.is_a?(String) || path_or_io.is_a?(Pathname)
  @content_type = opts.fetch(:content_type, DEFAULT_MIME).to_s
  @filename     = opts.fetch(:filename, filename_for(@io))
end

Instance Method Details

#closevoid

This method returns an undefined value.

Closes the underlying IO if it was opened by this instance

When the File was created from a String path or Pathname, the underlying file handle is closed. When created from an existing IO object, this is a no-op (the caller is responsible for closing it).

Examples:

file = FormData::File.new("/path/to/file.txt")
file.to_s
file.close


62
63
64
# File 'lib/http/form_data/file.rb', line 62

def close
  @io.close if @autoclose
end