0

I want generate unique ID for my rails-application. To send them to the user. SecureRandom-support ended for 1.9.3. The UUIDTool is good for the Admin-Tooken, but not for a short url-Restful ID like www.site.com/h6scre55x66

Is there an alternative for rails to SecureRandom?

Thanks

amarradi
  • 109
  • 3
  • 16

2 Answers2

8

SecureRandom is still the answer.

I'm not sure where you got the idea that SecureRandom has been removed or deprecated -- it's still available in 2.3.

John Ledbetter
  • 13,557
  • 1
  • 61
  • 80
  • Not only by SecureRandom, but in general, support for Ruby 1.9.3 has ended. – sawa Mar 09 '16 at 13:44
  • Right, but that has no bearing on how to generate a random token. You can still use SecureRandom in 2.1, 2.2, 2.3. Heck, you can still use it in 1.9.3. – John Ledbetter Mar 09 '16 at 13:46
3

If you want to have more control over the character set used for the random tokens, this extension to class String can be useful:

(it is part of the "Facets of Ruby" gem)

Using a larger character set can help if you want a shorter token.

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

Source: https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

Tilo
  • 33,354
  • 5
  • 79
  • 106
  • I uses your hint Tilo. Thanks a lot for your comment. For now it works fine for me. If my app goes online anyway, if to validate this part again. – amarradi Mar 11 '16 at 13:57
  • 1
    Make sure that your character set conforms with how you transmit the tokens - e.g. it might have to be URL-safe.. – Tilo Mar 11 '16 at 16:32
  • Yes, i'll check this. Thank you – amarradi Mar 23 '16 at 06:46