使用Rails生成神社宝石:使用上传端点生成版本吗?

时间:2019-04-08 19:47:00

标签: ruby-on-rails ruby shrine

我在Rails 5中使用Shrine gem。我启用了插件upload_endpoint,版本,处理和重新缓存。我希望在上传端点响应中获得生成的版本。

class VideoUploader < Shrine
  plugin :processing
  plugin :versions
  plugin :recache
  plugin :upload_endpoint

  plugin :upload_endpoint, rack_response: -> (uploaded_file, request) do

    # ??? I expected uploaded_file to have thumbnail version here ???

    body = { data: uploaded_file.data, url: uploaded_file.url }.to_json
    [201, { "Content-Type" => "application/json" }, [body]]
  end

  process(:recache) do |io, context|
    versions = { original: io }

    io.download do |original|
      screenshot = Tempfile.new(["screenshot", ".jpg"], binmode: true)
      movie = FFMPEG::Movie.new(original.path)
      movie.screenshot(screenshot.path)
      screenshot.open # refresh file descriptors

      versions[:thumbnail] = screenshot
    end

    versions
  end
end

为什么仅在保存整个记录时才发生进程回调进程(:recache)?以及如何在直接上传后立即生成版本?

1 个答案:

答案 0 :(得分:1)

:recache操作仅在将文件分配给模型实例时以及验证成功之后才发生。因此,recache插件不是您想要的。

每当Shrine上传文件时,它都会在该上传文件中包含一个:action参数,这与您注册process块时匹配。目前尚无记录,但是upload_endpoint包含action: :upload,因此只需使用process(:upload)

process(:upload) do |io, context|
  # ...
end

在您的:rack_response块中,uploaded_file现在将是已上传文件的哈希,因此您将无法在其上调用#data。但是您可以直接将它们包括在哈希中,它们应该自动转换为JSON。

  plugin :upload_endpoint, rack_response: -> (uploaded_file, request) do
    body = { data: uploaded_file, url: uploaded_file[:original].url }.to_json
    [201, { "Content-Type" => "application/json" }, [body]]
  end