PageRenderTime 52ms CodeModel.GetById 30ms app.highlight 2ms RepoModel.GetById 18ms app.codeStats 1ms

/app.fy

http://github.com/bakkdoor/shortefy
Unknown | 102 lines | 85 code | 17 blank | 0 comment | 0 complexity | c97e6639b796d37854355e5dfd9f16c6 MD5 | raw file
  1require("sha1")
  2require: "sinatra"
  3require: "html"
  4require: "redis"
  5
  6R = Redis Client new
  7
  8# CONFIGURATION
  9
 10configure: 'production with: { disable: 'show_errors }
 11configure: ['production, 'development] with: {
 12  enable: 'logging
 13}
 14
 15set: 'port to: 3000
 16
 17# HELPER METHODS
 18
 19# basic html layout
 20def with_layout: body {
 21  HTML new: @{
 22    html: @{
 23      head: @{
 24        title: "Shortefy v0.0.1"
 25      }
 26      body: |h| {
 27        h h1: "Shortefy"
 28        body call: [h]
 29      }
 30    }
 31  } to_s
 32}
 33
 34def with_link: id do: block else: else_block ({ "" }) {
 35  if: (R get: $ key: id) then: block else: else_block
 36}
 37
 38def key: id {
 39  "shortefy:#{id}"
 40}
 41
 42def count_key: id {
 43  key: id + ":count"
 44}
 45
 46def incr_counter: id {
 47  R incr: $ count_key: id
 48}
 49
 50def counter: id {
 51  R get: (count_key: id) . to_i
 52}
 53
 54# PAGE ROUTES
 55
 56get: "/" do: {
 57  with_layout: @{
 58    form: { action: "/new" method: "post" } with: @{
 59      fieldset: @{
 60        label: { for: "link" } with: "Link"
 61        br
 62        input: { type: "text" id: "link" name: "link" value: "http://" }
 63        br
 64        input: { type: "submit" value: "SAVE" }
 65      }
 66    }
 67  }
 68}
 69
 70post: "/new" do: {
 71  link = params['link]
 72  id = SHA1 new(link) to_s [[0, 10]]
 73  R set: (key: id, link)
 74  redirect: "/show/#{id}"
 75}
 76
 77get: "/show/:id" do: |id| {
 78  with_link: id do: |link| {
 79    with_layout: @{
 80      h1: "ID: #{id}"
 81      h2: "Clicks: #{counter: id}"
 82      h2: @{
 83        a: { href: link } with: link
 84      }
 85    }
 86  } else: {
 87    redirect: "/"
 88  }
 89}
 90
 91get: "/:id" do: |id| {
 92  with_link: id do: |link| {
 93    incr_counter: id
 94    redirect: link
 95  }
 96}
 97
 98not_found: {
 99  with_layout: @{
100    h1: "Sorry, this page does not exist :("
101  }
102}