A simple way to shorten Long URLS in RAILS

URL shortener solves the problem of sharing the long website URLs by shortening them into more portable size.
As we know most of the websites use services like Twitter(Tweet character limit 140), SMS to reach out to their users and also at the time of sending promotional SMS, it is a bit difficult to send long web URLs.To generate the shortened URLS, we have so many link shortening services as well, such as Goo.gl and Bitly and more.

The solution consists of two major parts:

  1. An activerecord model called shortened_url for storing the details of the shortened link including the click counter to store how many times a user visited the link and the information of the user to which the link belongs.
  2. A controller to redirect the user to the particular link, when they click on the shortened url. This controller will get the actual link from the database.

Details of the solution:

  • For maintaining maximum google juice to the original URL, the Url’s Controller does a 301 redirect which is the recommended type of redirect.
  • Instead of using model id, we are using a unique 6 character code.

Let’s build our URL shortener application

run command

way to shorten Long URLS in Rails

cd into application directory
Run bundle install as always

Now we need to create a table that will store our shortened urls

shorten Long URLS in RAILS

And then, add the below code into your migration file

shorten URLS in Rails

We need to write programming logic to generate the shortened URLS that we can add to our model called shortened_url.

Open the shortened_url.rb. It should look somewhat like the below mentioned file.

way to shorten URLS

Let’s create a controller to generate and manage redirection of shortened URLS

shorten Long URLS

And add code as mentioned below:

way to shorten Long URLS RAILS

We need to create the view files to get input from users and display the shortened url to them

Create views/shoretened_urls/index.html.erb

shorten URLS

One more file we need to create to display the shortened url

views/shoretened_urls/shortened.html.erb

shorten URLS in RAILS

Add the following line into your routes.rb file

shorten Long URLS in RAILS 1

And finally, we can check our URL shortener app is working fine

shorten Long URLS in RAILS

Open browser and visit the link localhost:3000

localhost

Copy paste any long url you want to short and click on SUBMIT button.You will see your url has been shortened.

local host

Thanks!

Save

Subscribe For Latest Updates

Related Posts

About Post Author

Leave a Comment

Your email address will not be published. Required fields are marked *