Skip to content

Instantly share code, notes, and snippets.

@dmerrick
Created January 31, 2019 21:16
Show Gist options
  • Save dmerrick/a8a33d2ec350905330add3bd579419aa to your computer and use it in GitHub Desktop.
Save dmerrick/a8a33d2ec350905330add3bd579419aa to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'sinatra'
require 'pp'
# env.oy/<random_str>
$data = {}
def generate_random_string(length = 5)
chars = ('a'..'z').to_a + ('0'..'9').to_a
(0...length).to_a.map{ chars[rand(chars.size)] }.join
end
def save(url)
if existing_short_string = $data.key(url)
return existing_short_string
end
random_string = ''
loop do
random_string = generate_random_string
break unless $data[random_string]
end
$data[random_string] = url
random_string
end
post '/' do
url = params[:url]
random_string = save(url)
pp $data
"your short url is available at /#{random_string}\n"
end
get '/:short_string' do
redirect $data[params[:short_string]]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment