hello_world.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # frozen_string_literal: true
  2. # Our Rack application to be executed by rackup
  3. class HelloWorld < Roda
  4. plugin :default_headers, 'Content-Type'=>'text/html; charset=utf-8'
  5. plugin :default_headers, 'Server'=>SERVER_STRING if SERVER_STRING
  6. plugin :hooks
  7. plugin :json
  8. plugin :render, :escape=>true, :layout_opts=>{ :cache_key=>'default_layout' }
  9. plugin :static_routing
  10. def bounded_queries
  11. queries = request['queries'].to_i
  12. return QUERIES_MIN if queries < QUERIES_MIN
  13. return QUERIES_MAX if queries > QUERIES_MAX
  14. queries
  15. end
  16. # Return a random number between 1 and MAX_PK
  17. def rand1
  18. rand(MAX_PK).succ
  19. end
  20. after do
  21. response['Date'] = Time.now.httpdate
  22. end
  23. # Test type 1: JSON serialization
  24. static_get '/json' do
  25. { :message=>'Hello, World!' }
  26. end
  27. # Test type 2: Single database query
  28. static_get '/db' do
  29. World.with_pk(rand1).values
  30. end
  31. # Test type 3: Multiple database queries
  32. static_get '/queries' do
  33. worlds =
  34. DB.synchronize do
  35. Array.new(bounded_queries) do
  36. World.with_pk(rand1)
  37. end
  38. end
  39. worlds.map!(&:values)
  40. end
  41. # Test type 4: Fortunes
  42. static_get '/fortunes' do
  43. @fortunes = Fortune.all
  44. @fortunes << Fortune.new(
  45. :id=>0,
  46. :message=>'Additional fortune added at request time.'
  47. )
  48. @fortunes.sort_by!(&:message)
  49. view :fortunes
  50. end
  51. # Test type 5: Database updates
  52. static_get '/updates' do
  53. worlds =
  54. DB.synchronize do
  55. Array.new(bounded_queries) do
  56. world = World.with_pk(rand1)
  57. world.update(:randomnumber=>rand1)
  58. world
  59. end
  60. end
  61. worlds.map!(&:values)
  62. end
  63. # Test type 6: Plaintext
  64. static_get '/plaintext' do
  65. response['Content-Type'] = 'text/plain'
  66. 'Hello, World!'
  67. end
  68. # Even though we don't have any non-static routes, this is still required.
  69. route { |_| }
  70. end