Class: Mistri::Content::Image

Inherits:
Data
  • Object
show all
Defined in:
lib/mistri/content.rb

Overview

A base64-encoded image with its MIME type.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data:, mime_type:) ⇒ Image

Returns a new instance of Image.



66
67
68
# File 'lib/mistri/content.rb', line 66

def initialize(data:, mime_type:)
  super(data: Content.freeze_string(data), mime_type: Content.freeze_string(mime_type))
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data

Returns:

  • (Object)

    the current value of data



52
53
54
# File 'lib/mistri/content.rb', line 52

def data
  @data
end

#mime_typeObject (readonly)

Returns the value of attribute mime_type

Returns:

  • (Object)

    the current value of mime_type



52
53
54
# File 'lib/mistri/content.rb', line 52

def mime_type
  @mime_type
end

Class Method Details

.from_bytes(bytes, mime_type:) ⇒ Object

Frozen at the pack site so the initializer's ownership check skips a second copy of what can be a multi-megabyte payload.



55
# File 'lib/mistri/content.rb', line 55

def self.from_bytes(bytes, mime_type:) = new(data: [bytes.b].pack("m0").freeze, mime_type:)

.from_data_uri(uri) ⇒ Object

Browsers, canvases, and upload pipelines hand images around as data: URIs; accept them directly.

Raises:

  • (ArgumentError)


59
60
61
62
63
64
# File 'lib/mistri/content.rb', line 59

def self.from_data_uri(uri)
  match = /\Adata:(?<mime>[^;,]+);base64,(?<data>.+)\z/m.match(uri.to_s)
  raise ArgumentError, "not a base64 data: URI" unless match

  new(data: match[:data].delete("\n").freeze, mime_type: match[:mime])
end

Instance Method Details

#bytesObject



72
# File 'lib/mistri/content.rb', line 72

def bytes = data.unpack1("m0")

#to_hObject



74
# File 'lib/mistri/content.rb', line 74

def to_h = { type: :image, data:, mime_type: }

#typeObject



70
# File 'lib/mistri/content.rb', line 70

def type = :image