Ruby on Rails - generating bit.ly style uuids

后端 未结 4 1849
天涯浪人
天涯浪人 2021-02-10 12:54

I\'m trying to generate UUIDs with the same style as bit.ly urls like:

http://bit.ly/aUekJP

or cloudapp ones:

http://cl.ly/1hVU         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-10 13:23

    I found this to be short and reliable:

    def create_uuid(prefix=nil)
      time   = (Time.now.to_f * 10_000_000).to_i
      jitter = rand(10_000_000) 
      key    = "#{jitter}#{time}".to_i.to_s(36)
      [prefix, key].compact.join('_')
    end
    

    This spits out unique keys that look like this: '3qaishe3gpp07w2m'
    Reduce the 'jitter' size to reduce the key size.

    Caveat: This is not guaranteed unique (use SecureRandom.uuid for that), but it is highly reliable:

    10_000_000.times.map {create_uuid}.uniq.length == 10_000_000
    

提交回复
热议问题