Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure prefixes are unique #86

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/prefixed_ids.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ def self.split_id(prefix_id, delimiter = PrefixedIds.delimiter)
[prefix, id]
end

def self.register_prefix(prefix, model:)
if (existing_model = PrefixedIds.models[prefix]) && existing_model != model
raise Error, "Prefix #{prefix} already defined for model #{model}"
end

PrefixedIds.models[prefix] = model
end

# Adds `has_prefix_id` method
module Rails
extend ActiveSupport::Concern
Expand All @@ -46,7 +54,7 @@ def has_prefix_id(prefix, override_find: true, override_param: true, fallback: t
self._prefix_id_fallback = fallback

# Register with PrefixedIds to support PrefixedIds#find
PrefixedIds.models[prefix.to_s] = self
PrefixedIds.register_prefix(prefix.to_s, model: self)
end
end
end
Expand Down
24 changes: 24 additions & 0 deletions test/prefixed_ids_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,28 @@ class PrefixedIdsTest < ActiveSupport::TestCase
assert_equal prefix_decoded, [1, 1]
end
end

test "register_prefix adds the expected prefix and model" do
model = Class.new(ApplicationRecord) do
def self.name
"TestModel"
end
end

PrefixedIds.register_prefix("test_model", model: model)
assert_equal model, PrefixedIds.models["test_model"]
end

test "has_prefix_id raises when prefix was already used" do
assert PrefixedIds.models.key?("user")
assert_raises PrefixedIds::Error do
Class.new(ApplicationRecord) do
def self.name
"TestModel"
end

has_prefix_id :user
end
end
end
end