Search code examples
ruby-on-railsrubyshrine

Shrine gem with Rails: generate versions with upload endpoint?


I use Shrine gem with Rails 5. I enabled plugins upload_endpoint, versions, processing and recache. I expected to get generated versions in upload endpoint response.

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

Why process callback process(:recache) happens only when saving whole record? And how to make it generate versions right after direct uploading?


Solution

  • The :recache action only happens when you assign a file to a model instance, and after validation succeeded. So the recache plugin is not what you want here.

    Whenever Shrine uploads a file, it includes an :action parameter in that upload, and this is what's matched when you register a process block. It's not currently documented, but the upload_endpoint includes action: :upload, so just use process(:upload):

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

    In your :rack_response block, uploaded_file will now be a hash of uploaded files, so you won't be able to call #data on it. But you can just include them in the hash directly, and they should automatically convert to 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