hello_world.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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"] = Time.now.httpdate
  16. response["Server"] = SERVER_STRING if SERVER_STRING
  17. #default content type
  18. response["Content-Type"] = "application/json"
  19. # Test type 1: JSON serialization
  20. r.is "json" do
  21. { message: "Hello, World!" }.to_json
  22. end
  23. # Test type 2: Single database query
  24. r.is "db" do
  25. World.with_pk(rand1).values.to_json
  26. end
  27. # Test type 3: Multiple database queries
  28. r.is "queries" do
  29. worlds =
  30. DB.synchronize do
  31. ALL_IDS.sample(bounded_queries).map do |id|
  32. World.with_pk(id).values
  33. end
  34. end
  35. worlds.to_json
  36. end
  37. # Test type 4: Fortunes
  38. r.is "fortunes" do
  39. response["Content-Type"] = "text/html; charset=utf-8"
  40. @fortunes = Fortune.all
  41. @fortunes << Fortune.new(
  42. id: 0,
  43. message: "Additional fortune added at request time."
  44. )
  45. @fortunes.sort_by!(&:message)
  46. view :fortunes
  47. end
  48. # Test type 5: Database updates
  49. r.is "updates" do
  50. worlds =
  51. DB.synchronize do
  52. ALL_IDS.sample(bounded_queries).map do |id|
  53. world = World.with_pk(id)
  54. new_value = rand1
  55. new_value = rand1 while new_value == world.randomnumber
  56. world.update(randomnumber: new_value)
  57. world.values
  58. end
  59. end
  60. worlds.to_json
  61. end
  62. # Test type 6: Plaintext
  63. r.is "plaintext" do
  64. response["Content-Type"] = "text/plain"
  65. "Hello, World!"
  66. end
  67. end
  68. end