hello_world.rb 2.1 KB

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