Latch::StoredFile
Inherits JSON::Serializable / Reference / Object
Represents a file that has been uploaded to a storage backend.
This class is JSON serializable and stores the file's location (id),
which storage it's in (storage), and associated metadata.
NOTE: The JSON format is compatible with Shrine.rb/Shrine.cr:
{
"id": "uploads/abc123.jpg",
"storage": "store",
"metadata": {
"filename": "photo.jpg",
"size": 102400,
"mime_type": "image/jpeg"
}
}
Constructors
Class methods
Instance methods
Aliases the []? method on the metadata property.
file["width"]?
# => 800
file["custom"]?
# => "value"
Downloads the file to a temporary file and returns it. As opposed to the block variant, this temporary file needs to be closed and deleted manually:
tempfile = file.download
tempfile.path
# => "/tmp/latch123456789.jpg"
tempfile.gets_to_end
# => "file content"
tempfile.close
tempfile.delete
Downloads to a tempfile, yields it to the block, then cleans up.
file.download do |tempfile|
process(tempfile.path)
end
# tempfile is automatically deleted
Returns the file extension based on the id or original filename.
NOTE: This method relies on filename? and filename which are generated
by the extract macro on Latch::Uploader. Concrete
StoredFile subclasses created through the Uploader.inherited macro
will have these methods available automatically.
file.extension?
# => "jpg"
Opens the file for reading. If a block is given, yields the IO and automatically closes it afterwards. Returns the block's return value.
file.open do |io|
io.gets_to_end
end
Opens the file and stores the IO handle internally for subsequent reads.
Remember to call close when done.
file.open
content = file.io.gets_to_end
file.close
Streams the file content to the given IO destination.
file.stream(response.output)
Returns the URL for accessing this file.
file.url
# => "https://bucket.s3.amazonaws.com/uploads/abc123.jpg"
# for presigned URLs
file.url(expires_in: 1.hour)
Returns the location for a named variant of this file. The variant is stored as a sibling under a subdirectory matching the original basename.
file = StoredFile.new(id: "uploads/abc123.jpg", ...)
file.variant_location("sizes_large")
# => "uploads/abc123/sizes_large.jpg"