Reputation: 2723
Let's say I have a domain, foobargoo.com
, and I recently registered fbg.co
so that I can add Url shortener to. I may have a lot of requests which has a route foobargoo.com/requests/:id
which may end up be more than 100 character, and I would like to use something like fbg.co/TxFj4
(which provides > 900 million strings) and redirect to the specific ID.
I am wondering if I can do it from within one rails codebase in the routes.rb
, or do I have to add a new repo just to do it?
Upvotes: 1
Views: 616
Reputation: 6545
It seems okay to have that in one code base. You certainly don't need to create separate project, but you may want to to speed up the redirection (for example by having light-weight Sinatra project instead of Rails).
In your routes.rb
you can add shortened routes like this:
constraints(host: 'fbg.co') do
get ':id', to: 'shortener#redirect'
end
Then use a simple action to handle redirects:
# shortener_controller.rb
class ShortenerController < ApplicationController
def redirect
redirect_to ShortLink.find_by_hash(params[:id]).url
end
end
Of course, you need a model which will store short URLs and map them to full URLs as well:
class ShortLink
# Migration for its creation is something like:
# t.string :hash
# t.string :path
def url
"foobargoo.com/#{path}"
end
end
Upvotes: 4