Module: Ask::DataURI
- Defined in:
- lib/ask/data_uri.rb
Overview
Build and parse data: URIs (RFC 2397).
Class Method Summary collapse
-
.decode(uri) ⇒ Array(String, String)
Parse a data URI into [mime_type, raw bytes].
-
.encode(data, mime_type: "application/octet-stream") ⇒ String
Encode raw bytes as a data URI.
-
.from_base64(base64, mime_type: "application/octet-stream") ⇒ String
Build a data URI from already-encoded base64 (e.g. content blocks that carry a
base64field).
Class Method Details
.decode(uri) ⇒ Array(String, String)
Parse a data URI into [mime_type, raw bytes].
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.
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).
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 |