我正在構建一個基於Sinatra的應用程序以部署在Heroku上。你可以把它想象成一個標準的URL縮寫,但舊的短代碼到期並可用於新的URL(我認識到這是一個愚蠢的概念,但它更容易解釋這種方式)。我將我的數據庫中的簡碼作爲一個整數表示,並重新定義它的閱讀器,從整數中給出一個簡短而唯一的字符串。數據庫鎖定:ActiveRecord + Heroku
由於某些行將被刪除,我已經編寫了所有短代碼整數的代碼,然後選擇第一個空的代碼來使用before_save
。不幸的是,如果我一個接一個地快速運行兩個實例,那麼我可以讓我的代碼創建具有相同簡碼整數的兩行,這顯然是不好的!我應該如何實現一個鎖定系統,以便我可以使用唯一的簡碼整數快速保存我的記錄?
這是我到目前爲止有:
Chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
CharLength = Chars.length
class Shorts < ActiveRecord::Base
before_save :gen_shortcode
after_save :done_shortcode
def shortcode
i = read_attribute(:shortcode).to_i
return '0' if i == 0
s = ''
while i > 0
s << Chars[i.modulo(CharLength)]
i /= 62
end
s
end
private
def gen_shortcode
shortcode = 0
self.class.find(:all,:order=>"shortcode ASC").each do |s|
if s.read_attribute(:shortcode).to_i != shortcode
# Begin locking?
break
end
shortcode += 1
end
write_attribute(:shortcode,shortcode)
end
def done_shortcode
# End Locking?
end
end