在Ruby/Rails中压缩十六进制字符串 [英] Compressing a hex string in Ruby/Rails

查看:100
本文介绍了在Ruby/Rails中压缩十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将MongoDB用作正在构建的Rails应用程序的后端.默认情况下,Mongo会为其记录生成24个字符的十六进制ID,以使分片更容易,因此我的URL看起来像这样:

I'm using MongoDB as a backend for a Rails app I'm building. Mongo, by default, generates 24-character hexadecimal ids for its records to make sharding easier, so my URLs wind up looking like:

example.com/companies/4b3fc1400de0690bf2000001/employees/4b3ea6e30de0691552000001

不是很漂亮.我想坚持使用Rails url约定,但也要将这些id保留在数据库中.我认为一个不错的折衷办法是使用更多字符将这些十六进制ID压缩为较短的集合,因此它们看起来像:

Which is not very pretty. I'd like to stick to the Rails url conventions, but also leave these ids as they are in the database. I think a happy compromise would be to compress these hex ids to shorter collections using more characters, so they'd look something like:

example.com/companies/3ewqkvr5nj/employees/9srbsjlb2r

然后在我的控制器中,反转压缩,获取原始的十六进制ID,然后使用该ID查找记录.

Then in my controller I'd reverse the compression, get the original hex id and use that to look up the record.

我的问题是,来回转换这些ID的最佳方法是什么?我当然希望它们尽可能短,但还要保证网址安全且易于转换.

My question is, what's the best way to convert these ids back and forth? I'd of course want them to be as short as possible, but also url-safe and simple to convert.

谢谢!

推荐答案

您可以使用比16高的基数来表示十六进制id,以使其字符串表示形式更短. Ruby内置支持使用从236的库.

You could represent a hexadecimal id in a base higher than 16 to make its string representation shorter. Ruby has built-in support for working with bases from 2 up to 36.

b36 = '4b3fc1400de0690bf2000001'.hex.to_s(36)
# => "29a6dblglcujcoeboqp"

要将其转换回24个字符的字符串,您可以执行以下操作:

To convert it back to a 24-character string you could do something like this:

'%024x' % b36.to_i(36)
# => "4b3fc1400de0690bf2000001"

要获得更好的压缩"效果,您可以使用比36高的基数来表示id.有Ruby库可以帮助您解决这一问题. all-your-base gem是一个这样的库.

To achieve better "compression" you could represent the id in base higher than 36. There are Ruby libraries that will help you with that. all-your-base gem is one such library.

我建议使用基本62表示形式,因为它仅使用0-9a-zA-Z字符,这意味着默认情况下它是URL安全的.

I recommend base 62 representation as it only uses 0-9, a-z and A-Z characters which means it is URL safe by default.

这篇关于在Ruby/Rails中压缩十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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