Skip to content

Instantly share code, notes, and snippets.

@mikker
Last active June 4, 2025 01:32
Show Gist options
  • Save mikker/7b29387cd859d28bc69e0677b34b9312 to your computer and use it in GitHub Desktop.
Save mikker/7b29387cd859d28bc69e0677b34b9312 to your computer and use it in GitHub Desktop.
# Usage:
#
# class Post < ApplicationRecord
# include HasNanoid
# has_nanoid
# end
#
module HasNanoid
extend ActiveSupport::Concern
ALPHABET = Random::Formatter::ALPHANUMERIC + %w[- _]
included do
before_create :generate_nanoid
validates :nanoid, uniqueness: true, allow_nil: true
def to_param
nanoid
end
end
class_methods do
def has_nanoid(prefix: nil, size: 8)
@nanoid_prefix = prefix || name.downcase.first(2)
@nanoid_size = size
end
attr_reader :nanoid_prefix, :nanoid_size
end
private
def generate_nanoid
prefix = self.class.nanoid_prefix
size = self.class.nanoid_size
loop do
id = SecureRandom.alphanumeric(size, chars: ALPHABET)
self.nanoid = "#{prefix}_#{id}"
break unless self.class.exists?(nanoid: nanoid)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment