跳至内容 跳至搜索

Active Storage Previewer

这是一个抽象基类,用于生成 blob 预览图的 previewer。有关具体子类的示例,请参阅 ActiveStorage::Previewer::MuPDFPreviewerActiveStorage::Previewer::VideoPreviewer

命名空间
方法
A
D
L
N
P
T

Attributes

[R] blob

类公共方法

accept?(blob)

在具体子类中实现此方法。当给定一个 previewer 可以从中生成图像的 blob 时,返回 true。

# File activestorage/lib/active_storage/previewer.rb, line 14
def self.accept?(blob)
  false
end

new(blob)

# File activestorage/lib/active_storage/previewer.rb, line 18
def initialize(blob)
  @blob = blob
end

实例公共方法

preview(**options)

在具体子类中重写此方法。它会 yield 一个可附加的预览图像(即 ActiveStorage::Attached::One#attach 接受的任何内容)。将其他选项传递给创建的底层 blob。

# File activestorage/lib/active_storage/previewer.rb, line 25
def preview(**options)
  raise NotImplementedError
end

实例私有方法

download_blob_to_tempfile(&block)

将 blob 下载到磁盘上的临时文件中。Yields 临时文件。

# File activestorage/lib/active_storage/previewer.rb, line 31
def download_blob_to_tempfile(&block) # :doc:
  blob.open tmpdir: tmpdir, &block
end

draw(*argv)

执行系统命令,将二进制输出捕获到临时文件中。Yields 临时文件。

使用此方法可以调用系统库(例如 muPDF 或 FFmpeg)来生成预览图像。生成的临时文件可以用作可附加 Hash 中 :io 的值。

def preview
  download_blob_to_tempfile do |input|
    draw "my-drawing-command", input.path, "--format", "png", "-" do |output|
      yield io: output, filename: "#{blob.filename.base}.png", content_type: "image/png"
    end
  end
end

输出临时文件在 tmpdir 返回的目录中打开。

# File activestorage/lib/active_storage/previewer.rb, line 49
def draw(*argv) # :doc:
  open_tempfile do |file|
    instrument :preview, key: blob.key do
      capture(*argv, to: file)
    end

    yield file
  end
end

logger()

# File activestorage/lib/active_storage/previewer.rb, line 93
def logger # :doc:
  ActiveStorage.logger
end

tmpdir()

# File activestorage/lib/active_storage/previewer.rb, line 97
def tmpdir # :doc:
  Dir.tmpdir
end