0

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を呼び出すことができます。

4

1 に答える 1

2

base62 ID を取得するように動作を変更しました。MongoMapper に自動インクリメント gem を作成しました

自動インクリメントされたIDを使用して、base62にエンコードします

この宝石は GitHub で入手できますhttps://github.com/phstc/mongomapper_id2

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

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

使用法

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

短縮URL

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

MongoDB find_and_modify http://www.mongodb.org/display/DOCS/findAndModify+Commandで競合状態を解決しました

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://pablocantero.com/blog/contatoにメッセージを送ってください。

于 2010-12-30T23:57:44.790 に答える