Class: Pikuri::Agent::History::Attachment

Inherits:
Data
  • Object
show all
Defined in:
lib/pikuri/agent/history.rb

Overview

A file the model was shown — an image from read, a pasted document. Holds the actual bytes; #stored_name is what #save calls it on disk.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mime:, filename:, bytes:) ⇒ Attachment

Returns a new instance of Attachment.

Parameters:

  • mime (String)

    e.g. "image/png"

  • filename (String)

    the name the model was shown

  • bytes (String)

    the file's contents; re-tagged binary, since the same image arrives as UTF-8 from a source file and as ASCII-8BIT from base64, and two differently-tagged copies of one PNG are not == — which would quietly break the round-trip property this whole type exists to hold.



112
113
114
# File 'lib/pikuri/agent/history.rb', line 112

def initialize(mime:, filename:, bytes:)
  super(mime: mime, filename: filename, bytes: bytes.b)
end

Instance Attribute Details

#bytesObject (readonly)

Returns the value of attribute bytes

Returns:

  • (Object)

    the current value of bytes



104
105
106
# File 'lib/pikuri/agent/history.rb', line 104

def bytes
  @bytes
end

#filenameObject (readonly)

Returns the value of attribute filename

Returns:

  • (Object)

    the current value of filename



104
105
106
# File 'lib/pikuri/agent/history.rb', line 104

def filename
  @filename
end

#mimeObject (readonly)

Returns the value of attribute mime

Returns:

  • (Object)

    the current value of mime



104
105
106
# File 'lib/pikuri/agent/history.rb', line 104

def mime
  @mime
end

Instance Method Details

#digestString

Returns SHA-256 of #bytes, hex.

Returns:

  • (String)

    SHA-256 of #bytes, hex.



132
133
134
# File 'lib/pikuri/agent/history.rb', line 132

def digest
  Digest::SHA256.hexdigest(bytes)
end

#stored_nameString

Content-addressed filename: the digest prefix makes it unique and self-verifying, so the same image read twice is stored once and a tampered file is caught at load.

Attachment.new(mime: 'image/png', filename: 'shot.png', bytes: png).stored_name
# => "3f9a1c8e2b-shot.png"

Returns:

  • (String)

    a bare basename, never a path.



124
125
126
127
128
129
# File 'lib/pikuri/agent/history.rb', line 124

def stored_name
  ext = File.extname(filename.to_s)
  stem = File.basename(filename.to_s, ext).gsub(/[^A-Za-z0-9._-]+/, '-')
  stem = 'attachment' if stem.empty?
  "#{digest[0, 10]}-#{stem}#{ext}"
end