Railsアプリのモデルに対して一意の非順次トークンを生成するアルゴリズムを使用しようとしています。
例えば:
MyModel.create.token #=> '183685'
MyModel.create.token #=> '456873'
MyModel.create.token #=> '813870'
これを処理するために考えられる唯一の方法は、ランダムなものを作成し、衝突をチェックして、再試行することです。これは私にはちょっと臭いコードのように思えます。
class MyModel < ActiveRecord::Base
before_create :set_token
def set_token
existing_model_count = nil
# Loop while we have a token that already belongs to an existing model.
while existing_model_count.nil? || existing_model_count > 0
random_token = TokenGenerator.random_token
existing_model_count = MyModel.where(token: random_token).count
end
# Loop exited, meaning we found an unused token.
self.token = random_token
end
end
while
不明な回数反復するループを含まない、これを行うためのより良い方法はありますか?
ここでの例は ruby ですが、これは一種の一般的なアルゴリズムの問題であり、どの言語にも当てはまる可能性があるため、他の言語での解決策を歓迎します。