跳到內容 跳到搜尋

Active Storage 預覽器

這是預覽器的抽象基底類別,用於從 blob 建立圖片。請參閱 ActiveStorage::Previewer::MuPDFPreviewerActiveStorage::Previewer::VideoPreviewer 以了解具體子類型的範例。

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

屬性

[R] blob

類別公開方法

accept?(blob)

在具體子類別中實作此方法。當給予預覽器可以從中產生圖片的 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)

在具體子類別中覆寫此方法。讓它產生一個可附加的預覽圖片(即 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 下載至磁碟上的臨時檔案。產生臨時檔案。

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

draw(*argv)

執行系統指令,將其二進制輸出擷取至臨時檔案。產生臨時檔案。

使用此方法作為某個系統函式庫(例如 muPDF 或 FFmpeg)的 Shell,以產生預覽圖片。產生的臨時檔案可以在可附加雜湊中用作 :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