Generating an Instagram- or Youtube-like unguessable string ID in ruby/ActiveRecord

前端 未结 3 924
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 12:12

Upon creating an instance of a given ActiveRecord model object, I need to generate a shortish (6-8 characters) unique string to use as an identifier in URLs, in the style of

3条回答
  •  情书的邮戳
    2020-12-09 12:24

    You can hash the id:

    Digest::MD5.hexdigest('1')[0..9]
    => "c4ca4238a0"
    Digest::MD5.hexdigest('2')[0..9]
    => "c81e728d9d"
    

    But somebody can still guess what you're doing and iterate that way. It's probably better to hash on the content

提交回复
热议问题