压缩红宝石中的大弦 [英] Compressing large string in ruby

查看:44
本文介绍了压缩红宝石中的大弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序(轨道上的红宝石),它发送一些YAML作为隐藏输入字段的值.

I have a web application(ruby on rails) that sends some YAML as the value of a hidden input field.

现在,我想减小发送到浏览器的文本的大小.什么是最有效的无损压缩形式,可以跨最少的数据发送数据?我可以在服务器端承担额外的压缩和解压缩成本.

Now I want to reduce the size of the text that is sent across to the browser. What is the most efficient form of lossless compression that would send across minimal data? I'm ok to incur additional cost of compression and decompression at the server side.

推荐答案

您可以在ruby核心中使用zlib实现来插入/删除数据:

You could use the zlib implementation in the ruby core to in/de-flate data:

require "zlib"
data = "some long yaml string" * 100
compressed_data = Zlib::Deflate.deflate(data)
#=> "x\x9C+\xCE\xCFMU\xC8\xC9\xCFKW\xA8L\xCC\xCDQ(.)\xCA\xCCK/\x1E\x15\x1C\x15\x1C\x15\x1C\x15\x1C\x15\x1C\x15\x1C\x15\x1C\x15D\x15\x04\x00\xB3G%\xA6"

您应该对压缩后的数据进行base64编码,以使其可打印:

You should base64-encode the compressed data to make it printable:

require 'base64'
encoded_data = Base64.encode64 compressed_data
#=> "eJwrzs9NVcjJz0tXqEzMzVEoLinKzEsvHhUcFRwVHBUcFRwVHBUcFUQVBACz\nRyWm\n"

稍后,在客户端,您可以使用 pako (JavaScript的zlib端口)来取回您的数据.此答案可能有助于您实现JS部分

Later, on the client-side, you might use pako (a zlib port to javascript) to get your data back. This answer probably helps you with implementing the JS part.

要让您了解其效果如何,以下是示例字符串的大小:

To give you an idea on how effective this is, here are the sizes of the example strings:

data.size            # 2100
compressed_data.size #   48
encoded_data.size    #   66

在客户端上进行压缩并在服务器上进行夸大处理时,反之亦然.

Same thing goes vice-versa when compressing on the client and inflating on the server.

Zlib::Inflate.inflate(Base64.decode64(encoded_data))
#=> "some long yaml stringsome long yaml str ... (shortened, as the string is long :)

免责声明:

  • ruby​​ zlib实现与pako实现兼容.但是我还没有尝试过.
  • 有关字符串大小的数字有些被骗.Zlib在这里真的很有效,因为字符串重复很多.现实生活中的数据通常不会重复那么多.
  • The ruby zlib implementation should be compatible with the pako implementation. But I have not tried it.
  • The numbers about string sizes are a little cheated. Zlib is really effective here, because the string repeats a lot. Real life data usually does not repeat as much.

这篇关于压缩红宝石中的大弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆