问题
I want to produce unique post identifier for posts in my blogging application.
Currently I am using SecureRandom.hex(10)
for generating unique post identifier for my blogging site but I am not sure is it safe SecureRandom for this purpose.
Is there any other way to do this?
回答1:
From the Ruby doc:
This library is an interface for secure random number generator which is suitable for generating session key in HTTP cookies, etc.
I had similar problem, I used Digest library.
Digest::MD5.hexdigest(post.title + post.created_at.to_s) #=> "b4809d..."
回答2:
If anyone looking for just unique numeric token. I'd rather use Time based approach. For not much-frequent requests (max one per second). You can use
Time.now.to_i
To get it in string Time.now.to_i.to_s
If you are dealing with frequent requests (thousands per second) while generating token. Use float conversation
Time.now.to_f #1532415770.0032046
To get it in string you can use Time.now.to_f.to_s.gsub(".", "")
although not recommended.
The chance of repentance of above value is close to null in current universe.
来源:https://stackoverflow.com/questions/34377748/how-to-generate-a-unique-random-id-for-post-in-ruby-on-rails-4