How to Create Unique Token in Ruby

In Ruby, you can use the SecureRandom class to generate secure random numbers for creating a token generator. Here is an example of a Ruby method:


require 'securerandom'

def generate_token(length, options = {})
options = {
uppercase: true,
lowercase: true,
numbers: true
}.merge(options)

charset = ''
charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if options[:uppercase]
charset += 'abcdefghijklmnopqrstuvwxyz' if options[:lowercase]
charset += '0123456789' if options[:numbers]

raise 'At least one character set must be selected.' if charset.empty?

token = ''
length.times do
token += charset[SecureRandom.random_number(charset.length)]
end

token
end

# Example usage:

token = generate_token(16, uppercase: true, lowercase: true, numbers: true)
puts "Generated token: #{token}"

In this Ruby method, generate_token accepts two parameters: length (the length of the token) and an options hash, which contains configurations for whether to include uppercase letters, lowercase letters, and numbers. Inside the method, a character set charset is constructed, and then the SecureRandom.random_number method is used to generate secure random numbers as indices. For each character of the token, a random index is generated and used to select a character from charset.

Please note that SecureRandom is part of Ruby's standard library, providing the functionality to generate secure random numbers, suitable for scenarios requiring high security. This class offers better randomness than rand and is cryptographically secure.

In the example usage, we call the generate_token method and print the generated token. If no character set is provided in the options hash, the function will raise an exception. You can adjust the parameters of the generate_token method to generate tokens of different lengths and character sets as needed.