PageRenderTime 31ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/app.fy

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