Ruby on Rails - generating bit.ly style uuids

后端 未结 4 756
再見小時候
再見小時候 2021-02-10 12:40

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:22

    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
    

提交回复
热议问题