class ActiveStorage::Previewer
examples of concrete subclasses.
ActiveStorage::Previewer::MuPDFPreviewer and ActiveStorage::Previewer::VideoPreviewer for
This is an abstract base class for previewers, which generate images from blobs. See
def self.accept?(blob)
Implement this method in a concrete subclass. Have it return true when given a blob from which
def self.accept?(blob) false end
def capture(*argv, to:)
def capture(*argv, to:) to.binmode open_tempfile do |err| IO.popen(argv, err: err) { |out| IO.copy_stream(out, to) } err.rewind unless $?.success? raise PreviewError, "#{argv.first} failed (status #{$?.exitstatus}): #{err.read.to_s.chomp}" end end to.rewind end
def download_blob_to_tempfile(&block) # :doc:
Downloads the blob to a tempfile on disk. Yields the tempfile.
def download_blob_to_tempfile(&block) # :doc: blob.open tmpdir: tmpdir, &block end
def draw(*argv) # :doc:
The output tempfile is opened in the directory returned by #tmpdir.
end
end
end
yield io: output, filename: "#{blob.filename.base}.png", content_type: "image/png"
draw "my-drawing-command", input.path, "--format", "png", "-" do |output|
download_blob_to_tempfile do |input|
def preview
generation. The resulting tempfile can be used as the +:io+ value in an attachable Hash:
Use this method to shell out to a system library (e.g. muPDF or FFmpeg) for preview image
Executes a system command, capturing its binary output in a tempfile. Yields the tempfile.
def draw(*argv) # :doc: open_tempfile do |file| instrument :preview, key: blob.key do capture(*argv, to: file) end yield file end end
def initialize(blob)
def initialize(blob) @blob = blob end
def instrument(operation, payload = {}, &block)
def instrument(operation, payload = {}, &block) ActiveSupport::Notifications.instrument "#{operation}.active_storage", payload, &block end
def logger # :doc:
def logger # :doc: ActiveStorage.logger end
def open_tempfile
def open_tempfile tempfile = Tempfile.open("ActiveStorage-", tmpdir) begin yield tempfile ensure tempfile.close! end end
def preview(**options)
anything accepted by ActiveStorage::Attached::One#attach). Pass the additional options to
Override this method in a concrete subclass. Have it yield an attachable preview image (i.e.
def preview(**options) raise NotImplementedError end
def tmpdir # :doc:
def tmpdir # :doc: Dir.tmpdir end