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\"",
#   "Accept-Ranges"       => "bytes"
# }
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_status, file_headers, file_body = record.attachment.to_rack_response

    response.status = file_status
    self.response_body = file_body


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\""


Partial responses are also supported via the :range parameter, which accepts a value of the Range request header.

env["HTTP_RANGE"] #=> "bytes=100-200"
status, headers, body = uploaded_file.to_rack_response(range: env["HTTP_RANGE"])
status                    #=> 206
headers["Content-Length"] #=> "101"
headers["Content-Range"]  #=> "bytes 100-200/1000"
body                      # partial content