timmillwood timmillwood - 1 year ago 77
Ruby Question

How would i generate a random and unique string in Ruby?

In a Ruby on Rails app I am working on I allow users to upload files and want to give these files a short, random alphanumeric name. (Eg 'g7jf8' or '3bp76'). What is the best way to do this?

I sas thinking of generating a hash / encrypted string from the original filename and timestamp. Then query the database to double check it doesnt exist. If it does, generate another and repeat.

The issue i see with this approach is if there is high propability of duplicate strings, it could add quite a lote of datbase load.

Answer Source

I use this :)

def generate_token(column, length = 64)
    self[column] = SecureRandom.urlsafe_base64 length
  end while Model.exists?(column => self[column])

Replace Model by your model name

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download