module MIME::DiscreteMediaFactory

Module used only for initializing derived DiscreteMedia objects.

Public Class Methods

create(file, content_type = nil) click to toggle source

Creates a corresponding DiscreteMedia subclass object for the given file based on file's filename extension. file can be a file path or File object.

content_type can be specified in order to override the auto detected content type. If the content_type cannot be detected, an UnknownContentError exception will be raised.

Creates and sets the singleton method path on the created object. The path method is utilized by other methods in the MIME library, therefore, eliminating redundant and explicit filename assignments.

Comparison Example

file1 = '/tmp/file1.txt'
file2 = '/tmp/file2.txt'
entity1 =
entity2 = DiscreteMediaFactory.create(file2)

mixed_msg =
mixed_msg.attach(entity1, 'filename' => file1)
mixed_msg.attach(entity2) # filename automatically added
# File lib/mime/discrete_media_factory.rb, line 40
def create file, content_type = nil
  if file.is_a? File
    cntnt =
    ctype = content_type || file_type(file.path)
    fname = file.path
    cntnt =
    ctype = content_type || file_type(file)
    fname = file

  type, subtype = ctype.to_s.split('/')
  if type.to_s.empty? || subtype.to_s.empty?
    raise UnknownContentError, "invalid content type: #{ctype}"

  media_obj = 
    case type
    when 'application';, subtype)
    when 'audio'      ;, subtype)
    when 'image'      ;, subtype)
    when 'text'       ;, subtype)
    when 'video'      ;, subtype)
    else raise UnknownContentError, "invalid content type: #{ctype}"

  media_obj.path = fname