Skip to content

Instantly share code, notes, and snippets.

@marcroberts
Created August 6, 2009 18:39
Show Gist options
  • Select an option

  • Save marcroberts/163484 to your computer and use it in GitHub Desktop.

Select an option

Save marcroberts/163484 to your computer and use it in GitHub Desktop.
Rack Middleware to generate short URLs for a model
# drop in /lib in a rails app
# replace MODEL with the model to run against
# enable in environment.rb with:
# config.middleware.use 'Shrtn::Middleware'
module Shrtn
class Helper
include Singleton
def initialize
@chars = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['-','_']
@chars -= %w(a e i o u A E I O U) # remove vowels to prevent actual (rude) words
@base = @chars.size
end
def generate_id id
localCount = id
result = ''
while localCount != 0
rem = localCount % @base
localCount = (localCount - rem) / @base
result = @chars[rem] + result
end
result
end
def parse_id str
id = 0
count = 0
str.reverse.each_char do |n|
id += (@base**count) * @chars.index(n)
count += 1
end
id
end
end
class Middleware
include ActionController::UrlWriter
def initialize app
@app = app
end
def call env
if env['PATH_INFO'] =~ /^\/s\/(.*)/
id = Shrtn::Helper.instance.parse_id($1)
if id.nil? || (obj = MODEL.find_by_id(id)).nil?
[404, {'Content-type' => 'text/plain'}, 'Not Found']
else
[301, {'Location' => MODEL_path(obj, :only_path => true) }, '']
end
else
@app.call env
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment