1

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?

Mr94
  • 143
  • 1
  • 15

2 Answers2

3

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.

Rajan Verma - Aarvy
  • 1,969
  • 18
  • 20
  • This seems like a good approach, @Aarvy. However I'm curious why the floating option has a better performance from the integer one? I'd expect both to be O(1) – Antonio Jun 18 '20 at 19:51
2

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..."
  • Is there any documentation for this function because I could not find it. Is it a problem if I use SecureRandom hash? – Mr94 Dec 20 '15 at 16:20
  • You can open this [page](http://ruby-doc.org/stdlib-2.1.0/libdoc/digest/rdoc/Digest.html) or run `ri Digest`. I think it is fine to use `SecureRandom`. – rezajatnika Dec 21 '15 at 13:12
  • I get "Could not find gem 'Digest' in any of the gem sources listed in your Gemfile." when I add 'Digest' or 'digest' to the gemfile and run `bundle install` – stevec May 26 '19 at 06:04
  • Also, if I try `gem install digest` it returns "ERROR: Could not find a valid gem 'digest' (>= 0) in any repository" – stevec May 26 '19 at 06:06