Using gzip compression in Sinatra with Ruby

Note. I had another similar question about how GZIP data using Ruby zlib was given a technical answer to and I didn’t feel that I could start developing this question since it was answered, although this question is related to this same thing ...

The following code (I believe) is a GZIP'ing static CSS file and storing the results in the result variable. But what should I do with this in the sense: how can I send this data back to the browser so that it is recognized as GZIP'ed, and not the original file size (for example, when checking my YSlow account I want it to be correctly labeled to make sure static resources are gzip).

 z = Zlib::Deflate.new(6, 31) z.deflate(File.read('public/Assets/Styles/build.css')) z.flush @result = z.finish # could also of done: result = z.deflate(file, Zlib::FINISH) z.close 

... It should be noted that in my previous question the defendant explained that Zlib::Deflate.deflate will not generate gzip-encoded data. It will only generate zlib-encoded data, so I will need to use Zlib::Deflate.new with a windowBits argument of 31 to start the gzip stream.

But when I run this code, I really don't know what to do with the result variable and its contents. There is no information on the Internet (what I can find) on how to send static resources encoded in GZIP to the browser (for example, JavaScript, CSS, HTML, etc.), which speeds up page loading. It seems that every Ruby article I read is based on who uses Ruby on Rails !!?

Any help really appreciated.

+8
ruby gzip zlib sinatra
source share
2 answers

After the zip file, you simply return the result and make sure to respond to the Content-Encoding: gzip header. Google has a nice, small introduction to gzip compression and what you should follow. Here is what you could do in Sinatra:

 get '/whatever' do headers['Content-Encoding'] = 'gzip' StringIO.new.tap do |io| gz = Zlib::GzipWriter.new(io) begin gz.write(File.read('public/Assets/Styles/build.css')) ensure gz.close end end.string end 

One final word of caution. You should probably choose this approach only for content created on the fly, or if you just want to use gzip compression in several places.

If, however, your goal is to serve most or even all of your static resources with gzip compression turned on, then there will be a much better solution to rely on what is already supported by your web server, rather than polluting your code with this detail . There is a good chance that you can enable gzip compression with some configuration settings. Here is an example of how this is done for nginx.

Another alternative would be to use the Rack :: Deflater middleware .

+13
source share

Just highlight the "Rack :: Deflater" method as the "answer" →

As mentioned in the comment above, just put the compression in config.ru

 use Rack::Deflater 

that's all!

+3
source share

All Articles