MimeMagic Ruby Library

repository·master·Indexed 19 days ago

https://github.com/mimemagicrb/mimemagic

A Ruby library for detecting MIME types using file extensions or content (magic bytes), relying on the Freedesktop.org shared-mime-info database. It provides methods to identify types via extension, path, or IO objects, allows for custom MIME type definitions, and includes helpers to inspect type properties and hierarchies.

Tokens
1.5K
Snippets
8
Records
9
Agent score
15%

What's inside MimeMagic

  1. Detect MIME types by extension, path, or content

    master

    MimeMagic provides several methods to identify file types. You can detect types based on a file extension, a file path, or by inspecting the file's actual content (magic bytes).

    • MimeMagic.by_extension(ext): Detects type using an extension string (e.g., 'html' or '.html').
    • MimeMagic.by_path(path): Detects type by looking at a file on disk.
    • MimeMagic.by_magic(io): Detects type by reading the content of an IO object (like a File handle).
    require 'mimemagic'
    
    # By extension
    MimeMagic.by_extension('html').text?
    MimeMagic.by_extension('.html').child_of? 'text/plain'
    
    # By path
    MimeMagic.by_path('filename.txt')
    
    # By content (magic bytes)
    MimeMagic.by_magic(File.open('test.html'))
  2. Install and configure the shared-mime-info dependency

    master

    MimeMagic requires the Freedesktop.org shared-mime-info database to function.

    Linux

    Install via your system's package manager. The database is typically located in the standard system path expected by the gem.

    macOS

    Install via Homebrew:

    brew install shared-mime-info

    Windows or Manual Installation

    If you cannot use a package manager, you must manually extract freedesktop.org.xml from a Debian package:

    1. Download the package from Debian packages.
    2. Ensure 7-Zip is installed.
    3. Run the following command to extract the required XML file:
    7z x -so shared-mime-info_2.0-1_amd64.deb data.tar | 7z e -sidata.tar "./usr/share/mime/packages/freedesktop.org.xml"
    1. Place freedesktop.org.xml in a stable location.
    2. Set the FREEDESKTOP_MIME_TYPES_PATH environment variable to the path of that file.

    Note: The file must remain at this location at runtime for the gem to work.

    brew install shared-mime-info
  3. Check MIME type categories and hierarchy

    master

    The MimeMagic instance provides helper methods to check the category of a file or its relationship to other types:

    • image?, audio?, video?: Returns true if the mediatype matches the category.
    • text?: Returns true if the mediatype is text or a child of text/plain.
    • child_of?(parent): Returns true if the current type is a subtype of the provided parent string.
    mime = MimeMagic.by_extension('jpg')
    
    mime.image?          # => true
    mime.child_of?('image') # => true
    
    text_mime = MimeMagic.by_extension('txt')
    text_mime.text?      # => true
  4. Lookup MIME type by magic content analysis

    master

    For files where the extension might be unreliable, use by_magic to analyze the file content. This is a slower operation as it inspects the actual bytes of the IO object.

    • by_magic(io): Returns the first matching MimeMagic object.
    • all_by_magic(io): Returns an array of all matching MimeMagic objects.
    File.open('file.unknown', 'rb') do |f|
      mime = MimeMagic.by_magic(f)
      puts mime.type if mime
    end
  5. Inspect MimeMagic type properties

    master

    Once you have a MimeMagic instance, you can inspect its components and metadata:

    • type: The full MIME type string (e.g., image/png).
    • mediatype: The primary type (e.g., image).
    • subtype: The specific subtype (e.g., png).
    • extensions: Returns an array of strings representing the file extensions associated with this type.
    • comment: Returns the descriptive comment string associated with the type.
    mime = MimeMagic.by_extension('png')
    puts mime.type      # => "image/png"
    puts mime.mediatype # => "image"
    puts mime.subtype   # => "png"
    puts mime.extensions # => ["png"]
  6. Add a custom MIME type

    master

    You can extend the MIME database at runtime using MimeMagic.add. This is useful for supporting proprietary or non-standard file formats.

    Arguments:

    • type: The full MIME type string (e.g., 'application/x-custom').
    • options: A hash containing:
      • :extensions: A single string or an array of strings representing file extensions.
      • :parents: A single string or an array of strings representing parent MIME types.
      • :magic: A Mime magic specification for content-based detection.
      • :comment: A descriptive string for the type.
    MimeMagic.add('application/x-my-format', {
      extensions: ['myext', 'customext'],
      parents: ['application'],
      comment: 'My custom file format'
    })
  7. Remove a MIME type from the dictionary

    master

    If you encounter impossible conflicts (e.g., a specific type incorrectly claiming an extension), you can remove a MIME type from the dictionary. This will also remove all associated extensions and magic specifications.

    MimeMagic.remove('application/x-gmc-link')
  8. Lookup MIME type by extension or path

    master

    You can resolve a MimeMagic object using a file extension or a full file path. The library handles extensions both with and without the leading dot (e.g., png or .png).

    # By extension
    MimeMagic.by_extension('png')
    
    # By path
    MimeMagic.by_path('/path/to/file.png')