Class: Discorb::File

Inherits:
Object
  • Object
show all
Defined in:
lib/discorb/file.rb

Overview

Represents a file to send as an attachment.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, filename = nil, content_type: nil) -> File

Creates a new file from IO.

Parameters:

  • io (#read)

    The IO of the file.

  • filename (String) (defaults to: nil)

    The filename of the file. If not set, path or object_id of the IO is used.

  • content_type (String) (defaults to: nil)

    The content type of the file. If not set, it is guessed from the filename. If failed to guess, it is set to application/octet-stream.



71
72
73
74
75
76
# File 'lib/discorb/file.rb', line 71

def initialize(io, filename = nil, content_type: nil)
  @io = io
  @filename = filename || (io.respond_to?(:path) ? io.path : io.object_id)
  @content_type = content_type || MIME::Types.type_for(@filename.to_s)[0].to_s
  @content_type = "application/octet-stream" if @content_type == ""
end

Instance Attribute Details

#content_type -> String

Returns The content type of the file. If not set, it is guessed from the filename.

Returns:

  • (String)

    The content type of the file. If not set, it is guessed from the filename.



61
62
63
# File 'lib/discorb/file.rb', line 61

def content_type
  @content_type
end

#filename -> String

Returns The filename of the file. If not set, path or object_id of the IO is used.

Returns:

  • (String)

    The filename of the file. If not set, path or object_id of the IO is used.



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

def filename
  @filename
end

#io -> #read

Returns The IO of the file.

Returns:

  • (#read)

    The IO of the file.



57
58
59
# File 'lib/discorb/file.rb', line 57

def io
  @io
end

Class Method Details

.from_string(string, filename: nil, content_type: nil) -> File

Creates a new file from a string.

Parameters:

  • string (String)

    The string to create the file from.

  • filename (String) (defaults to: nil)

    The filename of the file. object_id of the string is used if not set.

  • content_type (String) (defaults to: nil)

    The content type of the file. If not set, it is guessed from the filename.

Returns:

  • (File)

    The new file.



87
88
89
90
91
# File 'lib/discorb/file.rb', line 87

def self.from_string(string, filename: nil, content_type: nil)
  io = StringIO.new(string)
  filename ||= string.object_id.to_s + ".txt"
  new(io, filename, content_type: content_type)
end