Ruby+MongoMapperを使用してURL短縮アルゴリズムを作成しました
これは、最大3桁の単純なURL短縮アルゴリズムです http://pablocantero.com/###
各#は[az]または[AZ]または[0-9]にすることができます
このアルゴリズムでは、MongoDBで4つの属性を永続化する必要があります(MongoMapperを介して)
class ShortenerData
include MongoMapper::Document
VALUES = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
key :col_a, Integer
key :col_b, Integer
key :col_c, Integer
key :index, Integer
end
ShortenerDataを管理し、一意の識別子を生成するために別のクラスを作成しました
class Shortener
include Singleton
def get_unique
unique = nil
@shortener_data.reload
# some operations that can increment the attributes col_a, col_b, col_c and index
# ...
@shortener_data.save
unique
end
end
ショーターの使用法
Shortener.instance.get_unique
私の疑問は、get_uniqueを同期させる方法です。アプリはherokuにデプロイされ、同時リクエストはShortener.instance.get_uniqueを呼び出すことができます。