1

I've started creating a model based solution for creating short URLs, but I'm wondering if it wouldn't be better to do it in it's own collection (using mongoid) build an index for the tokens between models then search? Or if there's a gem that exists instead of rolling my own solution.

Right now i'm using Mongoid::Token which generates a unique token (ie cUaIxBu) for the particular collection and then using an additional letter (->(c)UaIxBu) to figure how which controller to route the particular request to.

Any ideas or pointers?

In this example alternatedoma.in/cUaIxBu would point to realdomain.com/cities/1234

routes

  get '/:id' => 'home#tiny_url', :constraints => { :domain => 'alternatedoma.in' }

controller

  def tiny_url
    case params[:id].slice!(0)
    when 'f'
      @article = Article.find_by_token(params[:id])
      redirect_to feature_url(@article)
    when 'c'
      @city = City.find_by_token(params[:id])
      redirect_to city_url(@city)
    when 'p'
      @place = Place.find_by_token(params[:id])
      redirect_to feature_url(@place)
    end
  end
Community
  • 1
  • 1
ere
  • 1,739
  • 3
  • 19
  • 41
  • never used it, but maybe you should check out mongoid_shortener https://github.com/siong1987/mongoid_shortener – holden Jan 26 '13 at 21:41

1 Answers1

1

We're employing an almost identical system in an application that I'm currently working on - and it seems to be working out okay (so far!). The only thing I could think of, is that you could boil down your LoC, as well as easily adding support for other models (if required) in the future:

supported_models = {:a => Article, :c => City, :p => Place}
prefix = params[:id].slice!(0).to_sym
if supported_models.has_key?(prefix)
  @obj = supported_models[prefix].find_by_token(params[:id])
  redirect_to send(:"#{supported_models[prefix].name.underscore}_url", @obj)
end

Obviously, this would require your routing helpers to follow the the same naming as your models. I.e: Article > article_url, City > city_url, etc.

theTRON
  • 9,608
  • 2
  • 32
  • 46