module Shrine::Plugins::RackResponse

  1. lib/shrine/plugins/rack_response.rb

The rack_response plugin allows you to convert an UploadedFile object into a triple consisting of status, headers, and body, suitable for returning as a response in a Rack-based application.

plugin :rack_response

To convert a Shrine::UploadedFile into a Rack response, simply call #to_rack_response:

status, headers, body = uploaded_file.to_rack_response
status  #=> 200
headers #=> {"Content-Length" => "100", "Content-Type" => "text/plain", "Content-Disposition" => "inline; filename=\"file.txt\""}
body    # object that responds to #each and #close

An example how this can be used in a Rails controller:

class FilesController < ActionController::Base
  def download
    # ...
    file_response = record.attachment.to_rack_response

    response.status = file_response[0]
    self.response_body = file_response[2]

By default the “Content-Disposition” header will use the inline disposition, but you can change it to attachment if you don't want the file to be rendered inside the browser:

status, headers, body = uploaded_file.to_rack_response(disposition: "attachment")
headers["Content-Disposition"] #=> "attachment; filename=\"file.txt\""