Generate UUID with SecureRandom.uuid
Ruby's SecureRandom module provides built-in UUID generation with no external dependencies. Part of Ruby's standard library since version 1.9, SecureRandom.uuid creates cryptographically secure random UUIDs (version 4) perfect for session tokens, database primary keys, and unique identifiers.
Built into Ruby Standard Library
No gem installation required! SecureRandom is included with every Ruby installation.
require 'securerandom'
uuid = SecureRandom.uuid
puts uuid # "550e8400-e29b-41d4-a716-446655440000"
Basic UUID Generation Examples
SecureRandom.uuid generates RFC 4122 compliant UUIDs with proper formatting including hyphens. Each call creates a unique, cryptographically random UUID suitable for production use in web applications, APIs, and database systems.
require 'securerandom'
# Generate single UUID v4
uuid = SecureRandom.uuid
puts uuid # "550e8400-e29b-41d4-a716-446655440000"
# Generate multiple UUIDs
uuids = 5.times.map { SecureRandom.uuid }
uuids.each { |u| puts u }
# Store in variable
session_id = SecureRandom.uuid
user_token = SecureRandom.uuid
# Uppercase format
upper_uuid = SecureRandom.uuid.upcase
# Remove hyphens
compact_uuid = SecureRandom.uuid.delete('-')
UUID Validation with Regular Expression
Validate UUID strings from user input or external sources using Ruby's pattern matching. This regex pattern checks for proper UUID v4 format including correct hyphen placement and valid hexadecimal characters in each section.
UUID_REGEX = /\A[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i
def valid_uuid?(str)
UUID_REGEX.match?(str)
end
# Test validation
puts valid_uuid?("550e8400-e29b-41d4-a716-446655440000") # true
puts valid_uuid?("not-a-uuid") # false
puts valid_uuid?("550E8400-E29B-41D4-A716-446655440000") # true (case insensitive)
# Validate and sanitize
def parse_uuid(str)
str = str.strip.downcase
valid_uuid?(str) ? str : nil
end
# Usage in method
def create_resource(uuid_string)
return { error: "Invalid UUID" } unless valid_uuid?(uuid_string)
{ id: uuid_string, created: true }
end
Rails Active Record UUID Primary Keys
Rails provides excellent support for UUID primary keys through migrations and model configurations. Using UUIDs instead of auto-incrementing integers offers better security, easier data merging across databases, and improved distributed system compatibility.
Migration with UUID Primary Key
# db/migrate/20250101000000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users, id: :uuid do |t|
t.string :name
t.string :email, null: false
t.timestamps
end
add_index :users, :email, unique: true
end
end
Model Configuration
# app/models/user.rb
class User < ApplicationRecord
# UUID is auto-generated for primary key
validates :email, presence: true, uniqueness: true
# Generate UUID before validation (if needed for custom logic)
before_validation :generate_uuid, on: :create
private
def generate_uuid
self.id ||= SecureRandom.uuid
end
end
# Usage
user = User.create(name: "Alice", email: "alice@example.com")
puts user.id # "550e8400-e29b-41d4-a716-446655440000"
PostgreSQL UUID Extension
# db/migrate/20250101000001_enable_pgcrypto.rb
class EnablePgcrypto < ActiveRecord::Migration[7.0]
def change
enable_extension 'pgcrypto'
end
end
# Then use gen_random_uuid() in PostgreSQL
# config/database.yml should use postgresql adapter
UUID Gem for Advanced Features
For UUID v1, v3, and v5 support beyond the standard library's v4 implementation, install the uuid gem. This provides timestamp-based UUIDs (v1) and namespace-based hash UUIDs (v3, v5) for deterministic ID generation.
Optional: uuid Gem Installation
# Gemfile
gem 'uuid'
# Using uuid gem
require 'uuid'
generator = UUID.new
# UUID v1 (timestamp-based)
uuid_v1 = generator.generate
# UUID v4 (random) - still prefer SecureRandom.uuid
uuid_v4 = UUID.generate
# Display UUID
puts uuid_v1 # Includes timestamp and MAC address
API Response with UUID Generation
When building REST APIs with Ruby, generate UUIDs for new resources and include them in JSON responses. This pattern works with Sinatra, Rails API mode, or any Ruby web framework for creating resource identifiers.
require 'securerandom'
require 'json'
class ApiController
def create_resource
resource = {
id: SecureRandom.uuid,
name: params[:name],
created_at: Time.now.iso8601
}
# Save to database...
{
status: 201,
body: resource.to_json,
headers: { 'Content-Type' => 'application/json' }
}
end
def validate_and_fetch(uuid_string)
unless valid_uuid?(uuid_string)
return {
status: 400,
body: { error: 'Invalid UUID format' }.to_json
}
end
# Fetch resource by UUID...
resource = find_resource(uuid_string)
{
status: 200,
body: resource.to_json
}
end
end