Created
June 25, 2013 03:06
-
-
Save kylescottmcgill/5855617 to your computer and use it in GitHub Desktop.
URL Shorty
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
| require "sinatra/base" | |
| require "sinatra/contrib/all" | |
| require "redis" | |
| require "slim" | |
| class App < Sinatra::Base | |
| register Sinatra::Contrib | |
| redis = Redis.new | |
| helpers do | |
| include Rack::Utils | |
| alias_method :h, :escape_html | |
| def random_string(length) | |
| rand(36**length).to_s(36) | |
| end | |
| end | |
| before do | |
| # @user = "Kyle Mcgill" | |
| # puts "before" | |
| end | |
| after do | |
| # puts "after" | |
| end | |
| route :get, :post, "/", :provides => [:html, :json] do | |
| if params[:url] && !params[:url].empty? | |
| @shortcode = random_string 5 | |
| redis.setnx "links:#{@shortcode}", params[:url] | |
| end | |
| respond_with slim :index do |t| | |
| t.html { slim :index } | |
| t.json { json({ | |
| welcome: "Welcome to sym.ly!", | |
| what: "sym.ly is yet another url shortner, for the example below, all that is required is the URL (u), try 'getting' /help for more details", | |
| whelp: "curl -v -H 'Content-Type: application/json' -X POST -d '{u: google.com, d: \"powered by JSON mwahaha\", r: uir789q, i: 1234, t: 60, p:0}' http://sym.ly/" }) | |
| } | |
| end | |
| end | |
| get "/:shortcode" do | |
| @url = redis.get "links:#{params[:shortcode]}" | |
| redirect @url || "/" | |
| end | |
| route :get, :post, 404, 500, :provides => [:html, :json] do | |
| "Your lost" | |
| end | |
| get '/help', :provides => [:html, :json] do | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment