hello_world.rb 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. worlds =
  55. ALL_IDS.sample(bounded_queries).map do |id|
  56. world = World.with_pk(id)
  57. new_value = rand1
  58. new_value = rand1 while new_value == world.randomnumber
  59. world.randomnumber = new_value
  60. world
  61. end
  62. World.batch_update(worlds)
  63. end
  64. worlds.map!(&:values).to_json
  65. end
  66. # Test type 6: Plaintext
  67. r.is "plaintext" do
  68. response[CONTENT_TYPE] = PLAINTEXT_TYPE
  69. "Hello, World!"
  70. end
  71. end
  72. end