hello_world.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. def bounded_queries
  7. queries = request.params["queries"].to_i
  8. queries.clamp(QUERIES_MIN, QUERIES_MAX)
  9. end
  10. # Return a random number between 1 and MAX_PK
  11. def rand1
  12. rand(MAX_PK) + 1
  13. end
  14. route do |r|
  15. response[DATE_HEADER] = Time.now.httpdate
  16. response[SERVER_HEADER] = SERVER_STRING if SERVER_STRING
  17. # Test type 1: JSON serialization
  18. r.is "json" do
  19. response[CONTENT_TYPE] = JSON_TYPE
  20. { message: "Hello, World!" }.to_json
  21. end
  22. # Test type 2: Single database query
  23. r.is "db" do
  24. response[CONTENT_TYPE] = JSON_TYPE
  25. World.with_pk(rand1).values.to_json
  26. end
  27. # Test type 3: Multiple database queries
  28. r.is "queries" do
  29. response[CONTENT_TYPE] = JSON_TYPE
  30. worlds =
  31. DB.synchronize do
  32. ALL_IDS.sample(bounded_queries).map do |id|
  33. World.with_pk(id).values
  34. end
  35. end
  36. worlds.to_json
  37. end
  38. # Test type 4: Fortunes
  39. r.is "fortunes" do
  40. response[CONTENT_TYPE] = HTML_TYPE
  41. @fortunes = Fortune.all
  42. @fortunes << Fortune.new(
  43. id: 0,
  44. message: "Additional fortune added at request time."
  45. )
  46. @fortunes.sort_by!(&:message)
  47. view :fortunes
  48. end
  49. # Test type 5: Database updates
  50. r.is "updates" do
  51. response[CONTENT_TYPE] = JSON_TYPE
  52. worlds =
  53. DB.synchronize do
  54. ALL_IDS.sample(bounded_queries).map do |id|
  55. world = World.with_pk(id)
  56. new_value = rand1
  57. new_value = rand1 while new_value == world.randomnumber
  58. world.update(randomnumber: new_value)
  59. world.values
  60. end
  61. end
  62. worlds.to_json
  63. end
  64. # Test type 6: Plaintext
  65. r.is "plaintext" do
  66. response[CONTENT_TYPE] = PLAINTEXT_TYPE
  67. "Hello, World!"
  68. end
  69. end
  70. end