How to generate a unique string that does not collide with ruby?

Question: Question:

When deciding the file name of the file uploaded by the user, I came up with a method of issuing an ID from the current time (milliseconds) so that the file names do not conflict.
After trying various things, the following code was completed, but since I just converted the current time value to a 62-ary number, the first character of the file is fixed at almost p2 like "p2dhXa6" and "p2d9Wco".

You can leave it as it is, but is there a way to generate an ID that is unique, visually random, and has a shorter string length, using the characters available in the filename?

Current code

def uniqid()
  def dec62(num)
    table = [('0'..'9'),('a'..'z'),('A'..'Z')].map{|c| c.to_a }.flatten
    num > 61 ? dec62(num/62)+table[num%62] : table[num%62]
  dec62( { self.to_i * 1000 + (usec/1000) })

Answer: Answer:


I think it's better to use SecureRandom. (I personally like SecureRandom.uuid because it's easy to see that it was randomly generated.)

require "securerandom"

# => "3366ab379a65448704fa7c7cab4b0843"
# => "4ab79521bf6712c1737b55f8393816b00996de29bed69257c5f6635bea899f9a"
# => "d1d145ae-2e1e-4d5f-8f0b-e962c47624e0"
# => "B7Yj6QUYaYtbM7gflqEbaQ"
# => "8CBbCIhp8hA"

URL-safe base64 (RFC 3548) is also "safe" as a file name because only "-" and "_" ("=" when padding is included) are used in addition to alphanumericals.


Tempfile is also a good choice for the purpose of creating temporary files. However, the directory is fixed. (The directory depends on the system.)

require "tempfile""moemoe")
# => #<File:/var/folders/sz/slkk1lv965lcpl8djdlq8qdc0000gn/T/moemoe20150124-19905-m2sbfw>

Serial number

Also, if you want to create a unique file name for saving, you can use serial numbers. For example, if you are using Ruby on Rails (ActiveRecord), it is a good idea to create a file name based on the model id . (To be precise, it may not be a serial number depending on the environment and operation contents, but it is guaranteed to be unique.)

class UserFile < ActiveRecord::Base
  FILE_STORE_DIR = Rails.root + "store/user_files"

  def filename
uf = UserFile.create
=> #<Pathname:/User/fate/rails/hoge/store/user_files/1>
Scroll to Top