Class: Rack::Deflater::GzipStream

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/deflater.rb

Overview

Body class used for gzip encoded responses.

Constant Summary collapse

BUFFER_LENGTH =
128 * 1_024

Instance Method Summary collapse

Constructor Details

#initialize(body, mtime, sync) ⇒ GzipStream

Initialize the gzip stream. Arguments:

body

Response body to compress with gzip

mtime

The modification time of the body, used to set the modification time in the gzip header.

sync

Whether to flush each gzip chunk as soon as it is ready.


91
92
93
94
95
# File 'lib/rack/deflater.rb', line 91

def initialize(body, mtime, sync)
  @body = body
  @mtime = mtime
  @sync = sync
end

Instance Method Details

#closeObject

Close the original body if possible.


127
128
129
# File 'lib/rack/deflater.rb', line 127

def close
  @body.close if @body.respond_to?(:close)
end

#each(&block) ⇒ Object

Yield gzip compressed strings to the given block.


98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/rack/deflater.rb', line 98

def each(&block)
  @writer = block
  gzip = ::Zlib::GzipWriter.new(self)
  gzip.mtime = @mtime if @mtime
  # @body.each is equivalent to @body.gets (slow)
  if @body.is_a? ::File # XXX: Should probably be ::IO
    while part = @body.read(BUFFER_LENGTH)
      gzip.write(part)
      gzip.flush if @sync
    end
  else
    @body.each { |part|
      # Skip empty strings, as they would result in no output,
      # and flushing empty parts would raise Zlib::BufError.
      next if part.empty?
      gzip.write(part)
      gzip.flush if @sync
    }
  end
ensure
  gzip.close
end

#write(data) ⇒ Object

Call the block passed to #each with the the gzipped data.


122
123
124
# File 'lib/rack/deflater.rb', line 122

def write(data)
  @writer.call(data)
end