Scanning database...
Tools
Articles

No matches found for ""

View All Results
Home Dev Lab ruby
Developer Lab

UUID in Ruby

Production-ready implementation guide with CSPRNG-backed code snippets.



Generate UUID in Ruby

SecureRandom.uuid is built into Ruby's standard library since Ruby 1.9 — zero dependencies, CSPRNG-backed, returns a lowercase hyphenated string directly.

Quick Reference

Method Version Sortable Use Case
SecureRandom.uuid v4 No General purpose — zero deps, built-in stdlib
UUIDTools::UUID.random_create v4 No UUIDTools gem — also supports v3/v5
UUIDTools::UUID.sha1_create v5 No Deterministic — namespace + name

Primary Implementation

Production Ready
ruby snippet
require 'securerandom'  # not needed in Rails — auto-required

# UUID v4 — random, CSPRNG-backed, returns lowercase string directly
id = SecureRandom.uuid
puts id
# → "f47ac10b-58cc-4372-a567-0e02b2c3d479"

# No hyphens
id_hex = SecureRandom.uuid.delete('-')
# → "f47ac10b58cc4372a5670e02b2c3d479"

# Uppercase
id_upper = SecureRandom.uuid.upcase
# → "F47AC10B-58CC-4372-A567-0E02B2C3D479"

# Generate multiple
ids = Array.new(5) { SecureRandom.uuid }

# Validate a UUID string
UUID_REGEX = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i

def valid_uuid?(str)
  UUID_REGEX.match?(str)
end

puts valid_uuid?(id) # → true

All UUID Versions

UUID v4 — Random (built-in stdlib)

ruby snippet
require 'securerandom'

# Returns a lowercase hyphenated string — no object wrapping
id = SecureRandom.uuid
# → "550e8400-e29b-41d4-a716-446655440000"

UUID v5 — Deterministic (UUIDTools gem)

ruby snippet
# gem install uuidtools
require 'uuidtools'

# SHA-1 hash of namespace + name — same inputs always produce the same UUID
id = UUIDTools::UUID.sha1_create(UUIDTools::UUID_DNS_NAMESPACE, 'example.com')
puts id.to_s # → always "cfbff0d1-9375-5685-968c-48ce8b15ae17"

Rails — ActiveRecord UUID primary key

ruby snippet
# config/initializers/generators.rb
Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

# db/migrate/20240101000000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
  def change
    create_table :users, id: :uuid do |t|
      t.string :name, null: false
      t.timestamps
    end
  end
end

Real-World Use Cases

1. Rails model with UUID primary key

ruby snippet
class Order < ApplicationRecord
  # Rails 7.1+ — use :uuid as primary key type in migration
  # The model itself needs no changes — Rails handles UUID generation

  before_create :set_public_id

  private

  def set_public_id
    self.public_id ||= SecureRandom.uuid
  end
end

2. Sidekiq job ID

ruby snippet
class ProcessOrderJob
  include Sidekiq::Job

  def perform(order_id)
    # Sidekiq assigns its own JID, but you can add a correlation ID
    correlation_id = SecureRandom.uuid
    Rails.logger.tagged(correlation_id) do
      order = Order.find(order_id)
      order.process!
    end
  end
end

3. API request tracing with Rack middleware

ruby snippet
class RequestIdMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    request_id = SecureRandom.uuid
    env['X-Request-ID'] = request_id
    status, headers, body = @app.call(env)
    headers['X-Request-ID'] = request_id
    [status, headers, body]
  end
end

# config/application.rb
config.middleware.use RequestIdMiddleware

Common Mistakes

Using rand or object_id for IDs

rand is not CSPRNG-backed and object_id is a memory address — both are predictable and not unique across processes. Always use SecureRandom.uuid.

Not enabling UUID primary keys in Rails migrations

By default, Rails uses integer PKs. To use UUIDs, set id: :uuid in create_table and enable the pgcrypto extension in PostgreSQL (enable_extension 'pgcrypto').

Forgetting require 'securerandom' outside Rails

In plain Ruby scripts, SecureRandom is not auto-loaded. Add require 'securerandom' at the top. In Rails, it is auto-required.

How It Works

SecureRandom.uuid calls SecureRandom.random_bytes(16) internally, which maps to /dev/urandom on Linux/macOS and CryptGenRandom on Windows. It then sets the version (4) and variant bits per RFC 4122.

Unlike Java or Rust, Ruby returns a plain lowercase String directly — no wrapper object. This makes it easy to use but means there is no built-in UUID type for validation.

Output Formats

SecureRandom.uuid

f47ac10b-58cc-4372-a567-0e02b2c3d479

No hyphens

SecureRandom.uuid.delete('-')

Uppercase

SecureRandom.uuid.upcase

Best Practices

Use SecureRandom.uuid for all new code — it's built-in and CSPRNG-backed.

In Rails, use id: :uuid in migrations and enable pgcrypto for PostgreSQL.

Validate incoming UUIDs with a regex before using them in queries.

Performance

Ruby generates roughly 1–2 million UUIDs/second. The bottleneck is the /dev/urandom syscall and string formatting.

For bulk generation, Array.new(n) { SecureRandom.uuid } is idiomatic. Avoid generating UUIDs in tight loops without batching DB inserts.

Installation

# No installation needed — stdlib since Ruby 1.9
require 'securerandom'
gem install uuidtools # for v3/v5 support

In Rails, SecureRandom is auto-required. No Gemfile entry needed for basic UUID v4.

Security

Entropy source: /dev/urandom on Linux/macOS, CryptGenRandom on Windows. Cryptographically secure.

Suitable for session tokens, CSRF tokens, and API keys. Never use rand or Time.now.to_i for security-sensitive IDs.