Skip to content

About

TypeID for Rails ActiveRecord with uuid typed primary keys

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

typeid_rails: TypeID identifiers for UUID primary keys in Rails

typeid_rails renders a 128-bit UUID as a TypeID, a short string that carries its own type tag, and parses it back. Its ActiveRecord attribute type keeps a plain uuid column in the database and exposes the TypeID to application code.

user_0wp9c9wd1d90msb3z67p5eb0v5
│    └─ the UUID, 26 Base32 characters
└────── a prefix naming the kind of resource

A UUID is a fine primary key and a poor thing to put in a URL. It is long, it looks like every other UUID, and pasting a user's ID where an order's ID belongs silently finds nothing. A TypeID is shorter, says what it identifies, and is obviously wrong in the wrong place.

The implementation passes the TypeID specification's test vectors (spec version 0.3.0). Optional settings relax decoding and equality for applications that already hand out Crockford Base32 identifiers decoded leniently.

Installation

bundle add typeid_rails

Requires Ruby 3.3 or later. The optional ActiveRecord integration is tested against ActiveRecord 7.1 and later.

Usage

require "typeid_rails"

TypeidRails.encode("1cb2589e-342d-4829-958f-e63d8ae58365", prefix: "user")
# => "user_0wp9c9wd1d90msb3z67p5eb0v5"

TypeidRails.to_uuid("user_0wp9c9wd1d90msb3z67p5eb0v5")
# => "1cb2589e-342d-4829-958f-e63d8ae58365"

to_uuid returns nil for anything malformed. When a bad identifier should be an error instead, parse it:

id = TypeidRails.parse("user_0wp9c9wd1d90msb3z67p5eb0v5")
id.uuid    # => "1cb2589e-342d-4829-958f-e63d8ae58365"
id.prefix  # => "user"
id.to_s    # => "user_0wp9c9wd1d90msb3z67p5eb0v5"

TypeidRails.parse("user_0WP9C9WD1D90MSB3Z67P5EB0V5")  # raises TypeidRails::InvalidFormatError

Pass expected_prefix: to reject identifiers that belong to another kind of resource. The result is nil rather than an exception, since a wrong prefix is usually a lookup that should miss:

TypeidRails.parse("user_0wp9c9wd1d90msb3z67p5eb0v5", expected_prefix: "org")  # => nil

Prefixes follow the TypeID grammar: lowercase ASCII letters and underscores, at most 63 characters, with no underscore at either end. An empty prefix is allowed and renders as the bare suffix. TypeidRails::Value is immutable. Decoding is strict by default. See Configuration to relax it.

To mint a new identifier without a database round-trip:

TypeidRails.generate(prefix: "user")              # => "user_..." from a UUIDv4
TypeidRails.generate(prefix: "user", version: 7)  # => "user_01m5a5kxrqeea9n21at57rtheq"

ActiveRecord

Under Rails the integration loads itself. Elsewhere, require "typeid_rails/active_record".

Declare a prefix on any model whose primary key is a UUID:

class User < ApplicationRecord
  include TypeidRails::Identifiable
  id_prefix "user"
end

User.first.id                                     # => "user_0wp9c9wd1d90msb3z67p5eb0v5"
User.find_by(id: "user_0wp9c9wd1d90msb3z67p5eb0v5")

The column still holds a plain UUID. Only the attribute is encoded. Raw UUIDs are accepted on assignment too, so seeds, migrations and hand-written queries do not have to encode first.

This gem never generates primary keys. That stays with the database (gen_random_uuid() or similar) or with your own code.

Foreign keys are handled by a second concern, included once in your base class. It is separate because a model with no public identifier of its own, such as a join table or an audit row, can still point at models that have one:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  include TypeidRails::AssociationSupport
end

class Membership < ApplicationRecord
  belongs_to :user  # user_id now reads and writes "user_..." identifiers
end

By default an identifier with the wrong prefix, or one that is malformed, collapses to the null UUID. It matches no row, and the lookup simply finds nothing. Pass strict: true to raise TypeidRails::PrefixMismatchError or TypeidRails::InvalidFormatError instead:

id_prefix "user", strict: true

A uuid column whose rows point at different models, with a sibling column naming which, has no single prefix. Type it with TypeidRails::PolymorphicType. It accepts an identifier under any prefix, or a raw UUID, and reads back the bare UUID, so the owning record supplies the prefix:

class Preference < ApplicationRecord
  OWNER_MODELS = {"user" => User, "org" => Organization}.freeze

  attribute :owner_id, TypeidRails::PolymorphicType.new

  def owner_id
    model = OWNER_MODELS[owner_type]
    model ? model.type_for_attribute("id").cast(super) : super
  end
end

Prefix registry

Declaring a prefix registers the model under it, so an identifier can be routed back to whatever owns it. This is useful when a token or an API path carries an identifier whose kind is not known ahead of time.

TypeidRails::Registry.model_for("user") # => User
TypeidRails::Registry.prefix_for(User)  # => "user"

Deterministic identifiers

derive_uuid turns any set of input parts into a stable UUID, so two systems that agree on the inputs arrive at the same identifier without talking to each other. Useful when records are mirrored across a boundary and both sides need to name them identically.

TypeidRails.derive_uuid("production", "users", "42")
# => "82b28cf0-404a-d9b3-1a45-70f9e81ea106"

Parts are joined with a NUL byte before hashing, so ("ab", "c") and ("a", "bc") derive different identifiers.

This requires the sha3 gem, which is not a dependency of this gem. Add it yourself if you use this feature:

gem "sha3"

The result is 128 raw bits of SHAKE128 output rendered in UUID shape. It is deliberately not an RFC 9562 UUID: no version or variant bits are set. This keeps derived identifiers stable forever, at the cost of them not being valid v4 or v7 UUIDs.

Configuration

# config/initializers/typeid_rails.rb
TypeidRails.configure do |config|
  config.fuzzy = false          # accept Crockford's lenient spellings when decoding
  config.equality = :typeid     # :typeid or :uuid, see below
  config.uuid_version = 4       # 4 or 7, used by generate
end

Each setting can be overridden where it applies: parse(..., fuzzy:), generate(..., version:), and id_prefix "user", fuzzy: or Type.new(prefix:, fuzzy:) for an attribute.

  • fuzzy: TypeID accepts only the lowercase alphabet. With fuzzy = true, the suffix also decodes in uppercase, and i/l read as 1, o as 0 and u as v, as in Crockford's Base32. The prefix is never relaxed, and the result always renders canonically.
  • equality: with :typeid, two values are equal when both the prefix and the UUID match, and a value equals a String only when it is the exact rendering. With :uuid, the prefix is ignored and a value also equals its raw UUID text.
  • uuid_version: TypeID recommends v7 so identifiers sort by creation time. A v7 UUID also reveals that time to anyone who holds the identifier, so the default is v4.

Per model

The attribute types can take fuzzy and strict from a model class instead, so they can be set on an abstract class rather than for the whole process:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  include TypeidRails::AssociationSupport
  typeid_options fuzzy: true, strict: true
end

class LegacyRecord < ApplicationRecord
  self.abstract_class = true
  typeid_options strict: false  # merged over the inherited options
end

An attribute takes the first setting found: the id_prefix argument, then the model's typeid_options, then the global configuration (fuzzy) or false (strict). A foreign key follows the options of the model that declares the belongs_to. typeid_options applies to attributes declared after it, so call it before id_prefix and belongs_to in the same class. equality and uuid_version act on values outside any model, and stay global.

To keep accepting identifiers an application already issued under the lenient Crockford rules, while migrating it towards TypeID:

TypeidRails.configure do |config|
  config.fuzzy = true
  config.equality = :uuid
end

Difference with the typeid gem

The typeid gem is a general Ruby implementation of TypeID that mints UUIDv7 identifiers. Use it when you need TypeIDs outside ActiveRecord and want no integration with models.

typeid_rails is built around existing UUID primary keys. It adds an attribute type so columns stay uuid while models read and write TypeIDs, a prefix registry, a type for polymorphic columns, and compatibility settings for identifiers already issued under lenient Crockford rules. The namespaces are different (TypeidRails and TypeID), so both gems can be loaded together.

Caveats

  • With fuzzy = true, the gem accepts strings that the TypeID spec requires to be rejected. Encoding is unaffected, and every identifier it renders is a valid TypeID.
  • generate mints UUIDv4 by default, while the spec recommends UUIDv7. Set uuid_version = 7 to follow it.
  • Value#== and #hash read the equality setting on every call. Changing it while values are held as hash keys leaves those hashes inconsistent.

Development

bin/setup                        # install dependencies
bundle exec rake                 # run the specs, including the TypeID test vectors
bundle exec rbs collection install
bundle exec steep check          # typecheck lib/ against sig/
hk check --all                   # run every linter, as CI does

Third-party code

The bit-buffer technique in TypeidRails::Base32 is adapted from the rotp gem, Copyright (c) 2011 Mark Percival, used under the MIT License. The notice is reproduced in lib/typeid_rails/base32.rb.

The test vectors in spec/fixtures/typeid/ are taken from the TypeID specification and used under the Apache License 2.0. They are not part of the published gem.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sorah/typeid_rails.

License

Copyright (c) 2026 Sorah Fukumori

The gem is available as open source under the terms of the MIT License.

About

TypeID for Rails ActiveRecord with uuid typed primary keys

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages