youtube之类的视频网站的11位随机id是如何生成的?类似于:http://www.youtube.com/watch?v=fY4Epc2XSGc 中的fY4Epc2XSGc
很多人都是自己实现安全随机数,类似以下的代码:
require 'digest/sha1'
def generate_temporary_password
self.password = Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by{rand}.join)
end
其实,rails已经为你做好了这一切。
你可以像这样去使用它:
require 'active_support/secure_random'
ActiveSupport::SecureRandom.hex(10)
=> "8a2cf0a838e64f6f85d1"
ActiveSupport::SecureRandom.base64(10)
=> "fUL81hGd77YyGg=="
|