Class: Brut::FrontEnd::Download

Inherits:
Object
  • Object
show all
Defined in:
lib/brut/front_end/download.rb

Overview

Represents a file the browser is going to download. This can be returned from a handler to initiate a download instead of rendering content.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename:, data:, content_type:, timestamp: false) ⇒ Download

Create a download

Parameters:

  • filename (String)

    The name (or base name) of the file name that will be downloaded.

  • data (Object)

    the data/contents of the file to download

  • content_type (String)

    the MIME content type to let the browser know what type of file this is.

  • timestamp (Time) (defaults to: false)

    if given, will be used with filename to set the filename of the file. This is useful if your users will download the same file mulitple times but you want to make each name different and meaningful.



15
16
17
18
19
20
# File 'lib/brut/front_end/download.rb', line 15

def initialize(filename:,data:,content_type:,timestamp: false)
  @filename     = filename
  @data         = data
  @content_type = content_type
  @timestamp    = timestamp
end

Instance Attribute Details

#dataObject (readonly)

Returns the data to be sent in the download.

Returns:

  • (Object)

    the data to be sent in the download



6
7
8
# File 'lib/brut/front_end/download.rb', line 6

def data
  @data
end

Instance Method Details

#headersObject

Access the necessary HTTP headers to allow this file to be downloaded



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/brut/front_end/download.rb', line 23

def headers
  filename = if @timestamp
               Time.now.strftime("%Y-%m-%dT%H-%M-%S") + "-" + @filename
             else
               @filename
             end
  {
    "content-disposition" => "attachment; filename=\"#{filename}\"",
    "content-type" => @content_type,
  }
end