Class: ElastomerClient::Middleware::Compress
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- ElastomerClient::Middleware::Compress
- Defined in:
- lib/elastomer_client/middleware/compress.rb
Overview
Request middleware that compresses request bodies with GZip for supported versions of Elasticsearch.
It will only compress when there is a request body that is a String. This middleware should be inserted after JSON serialization.
Constant Summary collapse
- CONTENT_ENCODING =
"Content-Encoding"
- GZIP =
"gzip"
- MIN_BYTES_FOR_COMPRESSION =
An Ethernet packet can hold 1500 bytes. No point in compressing anything smaller than that (plus some wiggle room).
1400
Instance Attribute Summary collapse
-
#compression ⇒ Object
readonly
Returns the value of attribute compression.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Compress
constructor
options - The Hash of “keyword” arguments.
Constructor Details
#initialize(app, options = {}) ⇒ Compress
options - The Hash of “keyword” arguments.
:compression - the compression level (0-9, default Zlib::DEFAULT_COMPRESSION)
21 22 23 24 |
# File 'lib/elastomer_client/middleware/compress.rb', line 21 def initialize(app, = {}) super(app) @compression = [:compression] || Zlib::DEFAULT_COMPRESSION end |
Instance Attribute Details
#compression ⇒ Object (readonly)
Returns the value of attribute compression.
17 18 19 |
# File 'lib/elastomer_client/middleware/compress.rb', line 17 def compression @compression end |
Instance Method Details
#call(env) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/elastomer_client/middleware/compress.rb', line 26 def call(env) if body = env[:body] if body.is_a?(String) && body.bytesize > MIN_BYTES_FOR_COMPRESSION output = StringIO.new output.set_encoding("BINARY") gz = Zlib::GzipWriter.new(output, compression, Zlib::DEFAULT_STRATEGY) gz.write(env[:body]) gz.close env[:body] = output.string env[:request_headers][CONTENT_ENCODING] = GZIP end end @app.call(env) end |