Class: HTTP::FormData::File

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

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

Returns:

  • (String)
"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

Parameters:

  • path_or_io (String, Pathname, untyped)
  • opts (Hash[Symbol, untyped], nil) (defaults to: nil)


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



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

def close
  @io.close if @autoclose
end

#filename_for(io) ⇒ String

Determines filename for the given IO

Parameters:

  • io (Object)

Returns:

  • (String)


86
87
88
89
90
91
92
# File 'lib/http/form_data/file.rb', line 86

def filename_for(io)
  if io.respond_to?(:path)
    ::File.basename(io.path)
  else
    "stream-#{io.object_id}"
  end
end

#make_io(path_or_io) ⇒ Object

Wraps path_or_io into an IO object

Parameters:

  • path_or_io (String, Pathname, untyped)

Returns:

  • (Object)


73
74
75
76
77
78
79
# File 'lib/http/form_data/file.rb', line 73

def make_io(path_or_io)
  case path_or_io
  when String   then ::File.new(path_or_io, binmode: true)
  when Pathname then path_or_io.open(binmode: true)
  else path_or_io
  end
end