2010-12-30 4 views
0

는 루비와 함께 단축 URL 알고리즘을 생성 + MongoMapper경쟁 조건, URL 축약 알고리즘/레일/MongoDB를/MongoMapper

그것은 최대 3 자리와 간단한 URL 축약 알고리즘의 http://pablocantero.com/###

각 #은 어디에서 할 수 있습니다 [AZ] 또는이 알고리즘의 [AZ] 또는 [0-9]

, 난

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 
,536 ( MongoMapper 통해) MongoDB의 4 개 개의 특성을 유지해야

나는 ShortenerData를 관리하고 나는 내 애플 배포 동기화 get_unique 될 것입니다 수있는 방법을 고유 식별자

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 

내 의심의 여지가입니다 Shortener를 사용을 생성하는 다른 클래스를 생성 heroku에서 동시 요청을 할 수 있습니다 Shortener.instance.get_unique

답변

2

base62 id. 내가 base62로 인코딩 자동 증가 ID로

을 MongoMapper하기 위해 자동 증가 보석을 만들어

주옥은 사용

movie = Movie.create(:title => 'Tropa de Elite') 
movie.id # BSON::ObjectId('4d1d150d30f2246bc6000001') 
movie.id2 # 3 
movie.to_base62 # d 

# app/models/movie.rb 
class Movie 
    include MongoMapper::Document 

    key :title, String 
    # Here is the mongomapper_id2 
    auto_increment! 
end 

GitHub의 https://github.com/phstc/mongomapper_id2 볼 수 있습니다 짧은 URL

# app/helpers/application_helper.rb 
def get_short_url model 
    "http://pablocantero.com/#{model.class.name.downcase}/#{model.to_base62}" 
end 

나는이 새로운 행동이 내가 경쟁 조건의 문제를 해결하면 MongoDB를 가진 경쟁 조건이

model = MongoMapper.database.collection(:incrementor). 
    find_and_modify(
    :query => {'model_name' => 'movies'}, 
    :update => {'$inc' => {:id2 => 1}}, :new => true) 

model[:id2] # returns the auto incremented_id 

http://www.mongodb.org/display/DOCS/findAndModify+Command을 find_and_modify 해결!

이 보석이 마음에 들면, 그것을 개선하는 데 도움주세요. 당신의 기고를하고 풀 요청으로 보내거나 그냥 메시지를 보내주십시오. http://pablocantero.com/blog/contato

관련 문제