Class: Zipline::TempfileBody

Inherits:
Object
  • Object
show all
Defined in:
lib/zipline/tempfile_body.rb

Overview

Contains a file handle which can be closed once the response finishes sending. It supports ‘to_path` so that `Rack::Sendfile` can intercept it

Constant Summary collapse

TEMPFILE_NAME_PREFIX =
"zipline-tf-body-"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, body) ⇒ TempfileBody

Returns a new instance of TempfileBody.

Parameters:

  • body (#each)

    the enumerable that yields bytes, usually a ‘RackBody`. The `body` will be read in full immediately and closed.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/zipline/tempfile_body.rb', line 10

def initialize(env, body)
  @tempfile = Tempfile.new(TEMPFILE_NAME_PREFIX)
  # Rack::TempfileReaper calls close! on tempfiles which get buffered
  # We wil assume that it works fine with Rack::Sendfile (i.e. the path
  # to the file getting served gets used before we unlink the tempfile)
  env['rack.tempfiles'] ||= []
  env['rack.tempfiles'] << @tempfile

  @tempfile.binmode

  body.each { |bytes| @tempfile << bytes }
  body.close if body.respond_to?(:close)

  @tempfile.flush
end

Instance Attribute Details

#tempfileObject (readonly)

Returns the value of attribute tempfile.



6
7
8
# File 'lib/zipline/tempfile_body.rb', line 6

def tempfile
  @tempfile
end

Instance Method Details

#eachvoid

This method returns an undefined value.

Stream the file’s contents if ‘Rack::Sendfile` isn’t present.



45
46
47
48
49
50
# File 'lib/zipline/tempfile_body.rb', line 45

def each
  @tempfile.rewind
  while chunk = @tempfile.read(16384)
    yield chunk
  end
end

#sizeInteger

Returns the size of the contained ‘Tempfile` so that a correct Content-Length header can be set

Returns:

  • (Integer)


30
31
32
# File 'lib/zipline/tempfile_body.rb', line 30

def size
  @tempfile.size
end

#to_pathString

Returns the path to the ‘Tempfile`, so that Rack::Sendfile can send this response using the downstream webserver

Returns:

  • (String)


38
39
40
# File 'lib/zipline/tempfile_body.rb', line 38

def to_path
  @tempfile.to_path
end