Skip to content

Instantly share code, notes, and snippets.

@cfcosta
Created November 5, 2011 04:48
Show Gist options
  • Save cfcosta/1341121 to your computer and use it in GitHub Desktop.
Save cfcosta/1341121 to your computer and use it in GitHub Desktop.
class LinkShortener
def call(env)
request = Rack::Request.new(env)
case env['REQUEST_PATH']
when '/shorten'
[200, {'Content-Type' => 'text/plain'}, shorten_link(request.params['src'])]
when /\/(.*)/
[200, {'Content-Type' => 'text/plain'}, unshorten_link($1)]
end
end
def unshorten_link(counter)
Maglev::PERSISTENT_ROOT["shortened:#{counter}"]
end
def shorten_link(link)
Maglev::PERSISTENT_ROOT[:last_counter] ||= 0
Maglev::PERSISTENT_ROOT[:last_counter] += 1
counter = Maglev::PERSISTENT_ROOT[:last_counter].to_s(36)
Maglev::PERSISTENT_ROOT["shortened:#{counter}"] = link
Maglev.commit_transaction
counter
end
end
run LinkShortener.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment