Module: DataURL

Defined in:
lib/dataurl.rb

Overview

Utilities for generating data URLs for use in HTML, CSS, etc.

Class Method Summary collapse

Class Method Details

.generate(mime_type:, content:) ⇒ String

Generate a data URL.

Parameters:

  • mime_type (String)

    media type of the data to encode

  • content (String)

    content to encode

Returns:

  • (String)

    RFC 2397-compliant data URL.



9
10
11
# File 'lib/dataurl.rb', line 9

def self.generate(mime_type:, content:)
  "data:#{mime_type};base64,#{[content].pack('m0')}"
end

.guess_mime(filename) ⇒ String

Guess the MIME type of a file using mailcap’s /etc/mime.types.

Parameters:

  • filename (String)

    filename to check against mime.types

Returns:

  • (String)

    media type or nil if it could not be detected



16
17
18
19
20
21
22
23
24
25
# File 'lib/dataurl.rb', line 16

def self.guess_mime(filename)
  extension = File.extname(filename)[1..-1].downcase

  File.foreach('/etc/mime.types') do |line|
    match = /\A([^#\s]+)\s+([^#]+)/.match(line)
    return match[1] if match && match[2].split.include?(extension)
  end

  nil
end