Module: Fastr::Compress

Includes:
Log
Defined in:
lib/fastr/compress/version.rb,
lib/fastr/compress.rb

Constant Summary collapse

VERSION =
"0.0.1"
ACCEPTABLE_ENCODINGS =
[:gzip, :deflate]

Class Method Summary collapse

Class Method Details

.after_boot(app) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/fastr/compress.rb', line 16

def self.after_boot(app)
  if HAS_ZLIB
    logger.debug "Compression plugin loaded."
  else
    logger.error "Compression plugin could not be loaded (zlib not found)."
  end
end

.after_dispatch(app, env, response) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/fastr/compress.rb', line 47

def self.after_dispatch(app, env, response)
  return response if not HAS_ZLIB
  return response if env['HTTP_ACCEPT_ENCODING'].nil?

  code, hdrs, body = response

  # Check to see what the acceptable content encodings are
  accept_encodings = env['HTTP_ACCEPT_ENCODING'].split(/,/).collect { |e| e.downcase.to_sym }
  encoding_format = nil

  accept_encodings.each do |enc|
    if ACCEPTABLE_ENCODINGS.include? enc
      encoding_format = enc
      break
    end
  end

  return response if encoding_format.nil?

  compress(response, encoding_format)
end

.compress(response, encoding) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fastr/compress.rb', line 24

def self.compress(response, encoding)
  code, hdrs, body = response

  # Set the content encoding header
  hdrs['Content-Encoding'] = encoding.to_s

  case encoding
  when :gzip
    fake_io = StringIO.new
    gz = Zlib::GzipWriter.new(fake_io, Zlib::DEFAULT_COMPRESSION, Zlib::DEFAULT_STRATEGY)
    gz.write(body.join(""))
    gz.close
    [code, hdrs, [fake_io.string]]
  when :deflate
    z = Zlib::Deflate.new(Zlib::DEFAULT_COMPRESSION)
    dst = z.deflate(body.join(""), Zlib::FINISH)
    z.close
    [code, hdrs, [dst.to_s]]
  else
    raise StandardError.new("not an acceptable encoding format: #{encoding}")
  end
end