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:
- 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.
- 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
cd into application directory
Run bundle install as always
Now we need to create a table that will store our shortened urls
And then, add the below code into your migration file
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.
Let’s create a controller to generate and manage redirection of shortened URLS
And add code as mentioned below:
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
One more file we need to create to display the shortened url
views/shoretened_urls/shortened.html.erb
Add the following line into your routes.rb file
And finally, we can check our URL shortener app is working fine
Open browser and visit the link localhost:3000
Copy paste any long url you want to short and click on SUBMIT button.You will see your url has been shortened.
Thanks!
Save