Module: Ask::DataURI

Defined in:
lib/ask/data_uri.rb

Overview

Build and parse data: URIs (RFC 2397).

Examples:

Ask::DataURI.encode("hello", mime_type: "text/plain")
# => "data:text/plain;base64,aGVsbG8="

Ask::DataURI.decode("data:text/plain;base64,aGVsbG8=")
# => ["text/plain", "hello"]

Class Method Summary collapse

Class Method Details

.decode(uri) ⇒ Array(String, String)

Parse a data URI into [mime_type, raw bytes].

Parameters:

  • uri (String)

    a data: URI

Returns:

  • (Array(String, String))

Raises:

  • (ArgumentError)

    when uri is not a data URI



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ask/data_uri.rb', line 42

def decode(uri)
  match = uri.to_s.match(%r{\Adata:([^;,]*)((?:;[^,]*)*),(.*)\z}m)
  raise ArgumentError, "Not a data URI: #{uri.to_s[0, 60].inspect}..." unless match

  mime = match[1].empty? ? "text/plain" : match[1]
  params = match[2]
  payload = match[3]
  if params.include?(";base64")
    [mime, Base64.strict_decode64(payload)]
  else
    [mime, URI.decode_www_form_component(payload)]
  end
end

.encode(data, mime_type: "application/octet-stream") ⇒ String

Encode raw bytes as a data URI.

Parameters:

  • data (String)

    raw bytes

  • mime_type (String) (defaults to: "application/octet-stream")

    MIME type

Returns:

  • (String)


23
24
25
# File 'lib/ask/data_uri.rb', line 23

def encode(data, mime_type: "application/octet-stream")
  from_base64(Base64.strict_encode64(data), mime_type: mime_type)
end

.from_base64(base64, mime_type: "application/octet-stream") ⇒ String

Build a data URI from already-encoded base64 (e.g. content blocks that carry a base64 field).

Parameters:

  • base64 (String)

    base64-encoded data

  • mime_type (String) (defaults to: "application/octet-stream")

    MIME type

Returns:

  • (String)


33
34
35
# File 'lib/ask/data_uri.rb', line 33

def from_base64(base64, mime_type: "application/octet-stream")
  "data:#{mime_type};base64,#{base64}"
end