Shortener is a Rails Engine Gem that makes it easy to create and interpret shortened URLs on your own domain from within your Rails application. Once installed Shortener will generate, store URLS and “unshorten” shortened URLs for your applications visitors, all whilst collecting basic usage metrics.

Overview

The majority of the shortener consists of two parts:

  • a model for storing the details of the shortened link (including the user the shortened link belongs to and counter that increments as the link is clicked);
  • a controller to accept incoming requests, grab the shortened link data out of the database and redirecting the visitors request to the target URL;

Some niceties of shortener:

  • The controller does a 301 redirect, which is the recommended type of redirect for maintaining maximum google juice to the original URL;
  • A unique code of is generated for each shortened link, instead of using the id of the shortened link record. This means that we can get more unique combinations than if we just used numbers;
  • The link records a count of how many times it has been “un-shortened”;
  • The link can be associated with a user, this allows for stats of the link usage for a particular user and other interesting things;

Installation

You can use the latest Rails gem with the latest Shortener gem. In your Gemfile:

  gem 'shortener'

After you install Shortener run the generator:

  rails generate shortener

This generator will create a migration to create the shortened_urls table where your shortened URLs will be stored.

Usage

To generate a Shortened URL object for the URL “www.jargonaut.net“ within your controller / models do the following:

  Shortener::ShortenedURL.generate("http://www.jargonaut.net")

or

  Shortener::ShortenedURL.generate("dealush.com")

To generate and display a shortened URL in your application use the helper method:

  shortened_url("dealush.com")

This will generate a shortened URL. store it to the db and return a string representing the shortened URL.

You can find the shortener gem on rubygems and complete source code of the shortener gem on github.

Any questions? Need help? Don’t be shy, you can post to the projects issues tracker.