timmillwood timmillwood - 4 months ago 12
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

I use this :)

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

Replace Model by your model name

Comments