Module: Lines::UniqueIDs

Included in:
Lines
Defined in:
lib/lines.rb

Instance Method Summary collapse

Instance Method Details

#id(collision_chance = 1.0/10e9, over_x_messages = 10e3) ⇒ Object

A small utility to generate unique IDs that are as short as possible.

It’s useful to link contextes together

See preshing.com/20110504/hash-collision-probabilities



400
401
402
403
404
405
406
407
# File 'lib/lines.rb', line 400

def id(collision_chance=1.0/10e9, over_x_messages=10e3)
  # Assuming that the distribution is perfectly random
  # how many bits do we need so that the chance of collision over_x_messages
  # is lower thant collision_chance ? 
  number_of_possible_numbers = (over_x_messages ** 2) / (2 * collision_chance)
  num_bytes = (Math.log2(number_of_possible_numbers) / 8).ceil
  SecureRandom.urlsafe_base64(num_bytes)
end