Class: FormData::File

Inherits:
Object
  • Object
show all
Defined in:
lib/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".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_or_io, opts = {}) ⇒ File

Returns a new instance of File

Parameters:

  • file_or_io (String, StringIO, File)

    Filename or IO instance.

  • opts (#to_h) (defaults to: {})

Options Hash (opts):

  • :mime_type (#to_s) — default: DEFAULT_MIME
  • :filename (#to_s)

    When file is a String, defaults to basename of file. When file is a File, defaults to basename of file. When file is a StringIO, defaults to "stream-{object_id}"

See Also:


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/form_data/file.rb', line 34

def initialize(file_or_io, opts = {})
  @file_or_io = file_or_io

  opts = FormData.ensure_hash opts

  @mime_type  = opts.fetch(:mime_type) { DEFAULT_MIME }
  @filename   = opts.fetch :filename do
    case file_or_io
    when String then ::File.basename file_or_io
    when ::File then ::File.basename file_or_io.path
    else             "stream-#{file_or_io.object_id}"
    end
  end
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename


24
25
26
# File 'lib/form_data/file.rb', line 24

def filename
  @filename
end

#mime_typeObject (readonly)

Returns the value of attribute mime_type


24
25
26
# File 'lib/form_data/file.rb', line 24

def mime_type
  @mime_type
end

Instance Method Details

#sizeFixnum

Returns content size.

Returns:

  • (Fixnum)

52
53
54
# File 'lib/form_data/file.rb', line 52

def size
  with_io(&:size)
end

#to_sString

Returns content of a file of IO.

Returns:

  • (String)

59
60
61
# File 'lib/form_data/file.rb', line 59

def to_s
  with_io(&:read)
end