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.



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

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



48
49
50
# File 'lib/mistri/content.rb', line 48

def data
  @data
end

#mime_typeObject (readonly)

Returns the value of attribute mime_type

Returns:

  • (Object)

    the current value of mime_type



48
49
50
# File 'lib/mistri/content.rb', line 48

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.



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

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)


55
56
57
58
59
60
# File 'lib/mistri/content.rb', line 55

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



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

def bytes = data.unpack1("m0")

#to_hObject



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

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

#typeObject



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

def type = :image