在 Rails 中使用 uuidtools 生成短的 UUID 字符串 [英] Generating a short UUID string using uuidtools In Rails

查看:79
本文介绍了在 Rails 中使用 uuidtools 生成短的 UUID 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须生成一个唯一的随机字符串,该字符串将存储在数据库中.为此,我使用了uuidtools" gem.然后在我的控制器中我添加了以下行:

I have to generate a unique and random string which is to be stored in database. For doing this I have used the "uuidtools" gem. Then in my controller I have added the following line:

require "uuidtools"

然后在我的控制器 create 方法中,我声明了一个temp"变量并生成了一个唯一且随机的uuid"字符串,如下所示:

and then in my controllers create method I have declared a 'temp' variable and generating a unique and random 'uuid' string like this:

temp=UUIDTools::UUID.random_create

正在创建这样的字符串:

which is creating a string like this one:

f58b1019-77b0-4d44-a389-b402bb3e6d50

现在我的问题是我必须让它简短,最好在 8-10 个字符内.现在我该怎么做??是否可以传递任何参数使其成为理想的长度字符串??

Now my problem is I have to make it short, preferably within 8-10 character. Now how do I do it?? Is it possible to pass any argument to make it a desirable length string??

提前致谢...

推荐答案

为此您不需要 uuidtools.为此,您可以使用安全随机.

You don't need uuidtools for this. You can use Secure Random for this.

[1] pry(main)> require "securerandom"
=> true
[2] pry(main)> SecureRandom.hex(20)
=> "82db4d707c4c5db3ebfc349da09c991b7ca0faa1"
[3] pry(main)> SecureRandom.base64(20)
=> "CECjUqNvPBaq0o4OuPy8RvsEoCY="

45 传递给 hex 将分别生成 8 个和 10 个字符的十六进制字符串.

Passing 4 and 5 to hex will generate 8 and 10 character hex strings respectively.

[5] pry(main)> SecureRandom.hex(4)
=> "a937ec91"
[6] pry(main)> SecureRandom.hex(5)
=> "98605bb20a"

这篇关于在 Rails 中使用 uuidtools 生成短的 UUID 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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