Created
November 5, 2011 04:48
-
-
Save cfcosta/1341121 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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