Simple Short URLs
Creating short URLs
I want to share with you an idea, or how to reinvent the wheel, if you need a short URL, but can’t use side solutions, such as goo.gl, and have a short domain. You can make a URL shorter on your own. First, we need to create a model with a destination path, parameter fields, and an appropriate controller. After that, we can route.
Then, we can make a redirect to a required path with saved parameters. If you need to create a very short URL for a tweet, for example, a digital :id
can eat too many symbols in the result URL. To make it shorter, we can convert an :id
number to a string (what, actually, URL shorters do). I have resolved this issue with the help of the Base64 standart. In our case, it’s just an array with characters and their IDs (codes). To convert an :id
number to a short string, first, we convert it into a URL with Base64. This is the example of the ShortUrl
model.
If you want to leave both route variants (a digital ID and a string ID), you can put a prefix before an encoded string (in this case, it’s the s
character) and use regular expression constraints in the route.
The number of characters is limited to five, because you can encode a really big number (1073741823) with five characters that can never be used. These are some examples of encoding.
Then, you should decode.
So, you can generate short URLs.
The result should look like this.
Further reading
- Some Tricks on How to Optimize an Auto-Complete Combobox Using ZK and Java
- Two Powerful Iterator Methods
About the author
Nikolai Sharangovich is an experienced Ruby on Rails developer with a deep understanding of the object-oriented design and modern software principles. He likes to collaborate with product people to achieve a maximum impact. Find him on GitHub.