Miniurl generator

1 06 2007

I got a small assignment to bang my head into for a couple of days.It was a url snipping application. I was also supposed to add Act_as_authenticated and and open_id authentication to the application.

There are two approaches to this problem:

1. I got this solution,over a discussion in Ruby On Rails spinoffs group in googlegroups.The approach is that, we create two methods in the model. a)initialize b) long_url. We use a before_filter and add it to the url controller ,generate a unique hash like initalizer code.Then we add initializer code to the index url to make a unique url from the given long url.Also, we store the long_url to the database and add a route in route.rb

2. There is a much simpler way to do this .I got it from Robby Russel’s site RobbyonRails , post of ruby url website creation.

We need to create 1 table,2 controllers and 1 model for that

The Model:

class Miniurl < ActiveRecord::Base

def self.gen_random(size=6)
chars = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890″
short_url = “”
srand
size.times do
pos = rand(chars.length)
short_url += chars[pos..pos]
end
short_url
end
end

The Go Controller:

class GoController < ApplicationController
def go
end

def index
@url = Miniurl.find_first(["short_url = ?", @params["id"]])
if @url['long_url']
redirect_to @url['long_url']
end
end
end

Miniurl Controller:

def create
@miniurl = Miniurl.new(params[:miniurl])
@miniurl['short_url'] = Miniurl.gen_random(6)
if @miniurl.save
flash[:notice] = ‘Miniurl was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

Then I generated the scaffold.Here we generate a random number using the gen_random(6) function of 6 digits.Then we add this to the index url and it works just fine

The bigger challange lies now, as I have to implement this code in RESTful and over edge rails.Will add that in this post soon.


Actions

Information

One response

1 06 2007
Satish Kota

Hey Saurabh,

Small addition might do good…

Since you use a random generator, there is all posibilities that it could repeat and is never unique… why not check for uniqueness before you save it else you could re-generate the randoms until you come out with the right stuff.

You might not see the uniqueness problem initially, but yes with time and when large number of random creations, the random value might tend to repeat itself…

Regards
Satish N Kota

Leave a comment