### Install dependencies and run tests Source: https://github.com/mimemagicrb/mimemagic/blob/master/README.md Commands to set up the development environment and execute the test suite for the MimeMagic gem. ```console bundle install bundle exec rake test ``` -------------------------------- ### Install MimeMagic Gem Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Instructions for installing the MimeMagic gem using Bundler and installing the shared-mime-info dependency on macOS. ```ruby # Gemfile gem 'mimemagic' ``` ```bash # Install the gem bundle install # On macOS, install the mime database dependency brew install shared-mime-info ``` -------------------------------- ### Complete File Detection Example (Ruby) Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Provides a robust function `detect_mime_type` in Ruby that combines both extension-based and magic-byte-based MIME type detection for comprehensive file identification. It handles file opening and returns a hash with various detection results. Requires the 'mimemagic' and 'file' libraries. ```ruby require 'mimemagic' def detect_mime_type(file_path) # First, try extension-based detection (fast) mime_by_ext = MimeMagic.by_path(file_path) # Then verify with magic-based detection (reliable) mime_by_magic = nil if File.exist?(file_path) File.open(file_path, 'rb') do |f| mime_by_magic = MimeMagic.by_magic(f) end end { by_extension: mime_by_ext&.to_s, by_magic: mime_by_magic&.to_s, is_text: mime_by_magic&.text? || mime_by_ext&.text?, is_image: mime_by_magic&.image? || mime_by_ext&.image?, extensions: (mime_by_magic || mime_by_ext)&.extensions, comment: (mime_by_magic || mime_by_ext)&.comment } end # Usage example result = detect_mime_type('photo.jpg') puts result.inspect # { # by_extension: "image/jpeg", # by_magic: "image/jpeg", # is_text: false, # is_image: true, # extensions: ["jpeg", "jpg", "jpe"], # comment: "JPEG image" # } # Detect potential extension spoofing result = detect_mime_type('fake_image.jpg') # Actually a text file if result[:by_extension] != result[:by_magic] puts "Warning: Extension doesn't match content!" puts "Extension suggests: #{result[:by_extension]}" puts "Content is actually: #{result[:by_magic]}" end ``` -------------------------------- ### Retrieve MIME Type Information (Ruby) Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Demonstrates how to get file extensions, human-readable comments, and mediatype/subtype components for a given MIME type using the mimemagic gem. It requires the 'mimemagic' library to be included. ```ruby require 'mimemagic' # Get file extensions for a MIME type html = MimeMagic.new('text/html') puts html.extensions.inspect # => ["htm", "html"] jpeg = MimeMagic.new('image/jpeg') puts jpeg.extensions.inspect # => ["jpeg", "jpg", "jpe"] # Get human-readable comment/description puts html.comment # => "HTML document" pdf = MimeMagic.new('application/pdf') puts pdf.comment # => "PDF document" # Get mediatype and subtype components mime = MimeMagic.new('application/json') puts mime.mediatype # => "application" puts mime.subtype # => "json" ``` -------------------------------- ### Detect MIME types and verify properties in Ruby Source: https://github.com/mimemagicrb/mimemagic/blob/master/README.md Demonstrates how to identify MIME types using file extensions or file content. It also shows how to check for MIME type hierarchies and add custom magic definitions. ```ruby require 'mimemagic' MimeMagic.by_extension('html').text? MimeMagic.by_extension('.html').child_of? 'text/plain' MimeMagic.by_path('filename.txt') MimeMagic.by_magic(File.open('test.html')) # Add custom magic definitions MimeMagic.add('application/x-custom', magic: [[0, 'custom', 'string']]) ``` -------------------------------- ### Find All Matching MIME Types by Content Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Demonstrates MimeMagic.all_by_magic for retrieving all possible MIME types that match the given file content. This is useful for formats like XLSX or ZIP, which can be interpreted as multiple MIME types. ```ruby require 'mimemagic' # Get all matching MIME types for an XLSX file File.open('spreadsheet.xlsx', 'rb') do |file| mimes = MimeMagic.all_by_magic(file) mimes.each do |mime| puts mime.to_s end # Output might include: # "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" # "application/zip" end # Get all matches for a ZIP-based format content = File.read('archive.zip') mimes = MimeMagic.all_by_magic(content) puts mimes.map(&:type).inspect # => ["application/zip"] ``` -------------------------------- ### MIME Type Checking Methods Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Explains how to use type-checking methods like text?, image?, audio?, video?, and child_of? on MimeMagic instances to categorize MIME types and check hierarchical relationships. ```ruby require 'mimemagic' # Text type detection html = MimeMagic.new('text/html') puts html.text? # => true (text/* types) puts html.image? # => false # XHTML is also considered text (child of text/plain) xhtml = MimeMagic.new('application/xhtml+xml') puts xhtml.text? # => true (inherits from text/plain) # Image type detection png = MimeMagic.new('image/png') puts png.image? # => true puts png.text? # => false # Audio type detection mp3 = MimeMagic.new('audio/mpeg') puts mp3.audio? # => true # Video type detection mp4 = MimeMagic.new('video/mp4') puts mp4.video? # => true # Check MIME type hierarchy html = MimeMagic.new('text/html') puts html.child_of?('text/plain') # => true (HTML inherits from text/plain) java = MimeMagic.new('text/x-java') puts java.child_of?('text/plain') # => true ``` -------------------------------- ### Lookup MIME Type by File Extension Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Demonstrates how to use MimeMagic.by_extension to find the MIME type based on a file's extension. It handles extensions with or without a leading dot and returns nil for unknown extensions. ```ruby require 'mimemagic' # Lookup by extension (with or without leading dot) mime = MimeMagic.by_extension('html') puts mime.to_s # => "text/html" puts mime.type # => "text/html" puts mime.mediatype # => "text" puts mime.subtype # => "html" # With leading dot mime = MimeMagic.by_extension('.png') puts mime.to_s # => "image/png" # Using symbols also works mime = MimeMagic.by_extension(:json) puts mime.to_s # => "application/json" # Returns nil for unknown extensions result = MimeMagic.by_extension('unknown123') puts result.nil? # => true ``` -------------------------------- ### Register Custom MIME Types (Ruby) Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Shows how to add new MIME types to the mimemagic database. This includes defining extensions, parent types, comments, and crucially, magic byte patterns for detection. The 'mimemagic' library must be required. ```ruby require 'mimemagic' # Add a simple custom MIME type with extensions MimeMagic.add('application/x-custom-format', extensions: %w[cust custom], parents: 'application/octet-stream', comment: 'Custom Application Format' ) # Now it can be detected by extension mime = MimeMagic.by_extension('cust') puts mime.to_s # => "application/x-custom-format" puts mime.comment # => "Custom Application Format" puts mime.extensions # => ["cust", "custom"] # Add a custom type with magic byte detection MimeMagic.add('application/x-myformat', extensions: ['myf'], parents: 'application/xml', magic: [ [0, 'MYFORMAT'], # Match "MYFORMAT" at byte offset 0 [0, "\x00\x01\x02\x03"] # Or match these bytes at offset 0 ] ) # Detect by magic bytes content = "MYFORMAT version 1.0 data here..." mime = MimeMagic.by_magic(content) puts mime.to_s # => "application/x-myformat" # Inherits from parent type puts mime.child_of?('text/plain') # => true (via application/xml) # Complex magic with offset ranges and nested conditions MimeMagic.add('application/x-complex', magic: [ [0, 'HEADER'], # Match at position 0 [10..20, 'MARKER'], # Match anywhere from position 10 to 20 [4, 'DATA', [[0, 'A'], [0, 'B']]] # Match "DATA" at 4 AND ("A" or "B" at 0) ] ) ``` -------------------------------- ### Lookup MIME Type by File Path Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Shows how to use MimeMagic.by_path to determine a file's MIME type by analyzing its filename or full path. The method extracts the extension and performs a lookup, returning nil if the extension is unrecognized. ```ruby require 'mimemagic' # Detect from full file path mime = MimeMagic.by_path('/var/www/assets/styles.css') puts mime.to_s # => "text/css" # Detect from filename only mime = MimeMagic.by_path('document.pdf') puts mime.to_s # => "application/pdf" # Works with any path format mime = MimeMagic.by_path('uploads/images/photo.jpeg') puts mime.to_s # => "image/jpeg" # Returns nil if extension is unknown result = MimeMagic.by_path('/path/to/file.unknownext') puts result.nil? # => true ``` -------------------------------- ### Lookup MIME Type by File Content (Magic Bytes) Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Illustrates using MimeMagic.by_magic to detect MIME types by analyzing the file's content (magic bytes). This method accepts file handles, raw strings, or IO-like objects and is more reliable for content verification than extension-based lookups. ```ruby require 'mimemagic' # Detect from file handle File.open('image.png', 'rb') do |file| mime = MimeMagic.by_magic(file) puts mime.to_s # => "image/png" end # Detect from raw string content png_header = "\x89PNG\r\n\x1a\n" mime = MimeMagic.by_magic(png_header) puts mime.to_s # => "image/png" # Detect from StringIO require 'stringio' io = StringIO.new(File.read('document.pdf')) mime = MimeMagic.by_magic(io) puts mime.to_s # => "application/pdf" # Works with any IO-like object that responds to :read # Returns nil if content doesn't match any known magic patterns unknown_content = "random bytes here" result = MimeMagic.by_magic(unknown_content) puts result.nil? # => true (if no magic match found) ``` -------------------------------- ### Remove MIME Types (Ruby) Source: https://context7.com/mimemagicrb/mimemagic/llms.txt Illustrates how to remove a registered MIME type from the mimemagic database, effectively disabling its detection via extensions or magic bytes. This is useful for managing conflicts or cleaning up the database. Requires the 'mimemagic' library. ```ruby require 'mimemagic' # Check that the type exists mime = MimeMagic.by_extension('html') puts mime.to_s # => "text/html" # Remove the MIME type MimeMagic.remove('text/html') # Now lookups return nil result = MimeMagic.by_extension('html') puts result.nil? # => true # Useful for resolving conflicts with problematic MIME types # Example: Remove a conflicting type before adding your own MimeMagic.remove('application/x-gmc-link') MimeMagic.add('application/x-my-link', extensions: ['gmc'], comment: 'My Link Format' ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.