我想爲我的rails應用程序生成唯一的ID。將它們發送給用戶。 SecureRandom - 支持1.9.3結束。 UUIDTool適用於Admin-Tooken,但不適用於較短的網址-Remful ID,例如www.site.com/h6scre55x66如何在Ruby中生成隨機令牌
是否有替代SecureRandom的導軌?
謝謝
我想爲我的rails應用程序生成唯一的ID。將它們發送給用戶。 SecureRandom - 支持1.9.3結束。 UUIDTool適用於Admin-Tooken,但不適用於較短的網址-Remful ID,例如www.site.com/h6scre55x66如何在Ruby中生成隨機令牌
是否有替代SecureRandom的導軌?
謝謝
如果你想擁有超過用於隨機令牌的字符集更多的控制,這擴展String
類可能是有用的:
(它是「紅寶石刻面的」寶石的一部分)
如果您想要較短的標記,則使用較大的字符集可以提供幫助。
class String
# Create a random String of given length, using given character set
#
# Character set is an Array which can contain Ranges, Arrays, Characters
#
# Examples
#
# String.random
# => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
#
# String.random(10)
# => "t8BIna341S"
#
# String.random(10, ['a'..'z'])
# => "nstpvixfri"
#
# String.random(10, ['0'..'9'])
# => "0982541042"
#
# String.random(10, ['0'..'9','A'..'F'])
# => "3EBF48AD3D"
#
# BASE64_CHAR_SET = ["A".."Z", "a".."z", "0".."9", '_', '-']
# String.random(10, BASE64_CHAR_SET)
# => "xM_1t3qcNn"
#
# SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
# BASE91_CHAR_SET = ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
# String.random(10, BASE91_CHAR_SET)
# => "S(Z]z,J{v;"
#
def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
Array.new(len){ chars.sample }.join
end
end
__support結束了1.9.3 .__顯示的證明吧。 –
@Зелёныйhttps://www.ruby-lang.org/zh/news/2015/02/23/support-for-ruby-1-9-3-has-ended/ – sawa
它是關於__SecureRandom-support ended__或ruby版? –