Generating a short UUID string using uuidtools In Rails

后端 未结 2 2056
忘了有多久
忘了有多久 2020-12-30 02:06

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 fol

2条回答
  •  执念已碎
    2020-12-30 02:47

    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="
    

    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"
    

提交回复
热议问题