hello_world.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # frozen_string_literal: true
  2. # Our Rack application to be executed by rackup
  3. class HelloWorld < Sinatra::Base
  4. configure do
  5. # Static file serving is ostensibly disabled in modular mode but Sinatra
  6. # still calls an expensive Proc on every request...
  7. disable :static
  8. # XSS, CSRF, IP spoofing, etc. protection are not explicitly required
  9. disable :protection
  10. # Only add the charset parameter to specific content types per the requirements
  11. set :add_charset, [mime_type(:html)]
  12. end
  13. helpers do
  14. def bounded_queries
  15. queries = params[:queries].to_i
  16. queries.clamp(QUERIES_MIN, QUERIES_MAX)
  17. end
  18. def json(data)
  19. content_type :json
  20. JSON.fast_generate(data)
  21. end
  22. # Return a random number between 1 and MAX_PK
  23. def rand1
  24. rand(MAX_PK).succ
  25. end
  26. end
  27. after do
  28. response['Date'] = Time.now.httpdate
  29. end
  30. after do
  31. response['Server'] = SERVER_STRING
  32. end if SERVER_STRING
  33. # Test type 1: JSON serialization
  34. get '/json' do
  35. json message: 'Hello, World!'
  36. end
  37. # Test type 2: Single database query
  38. get '/db' do
  39. world =
  40. ActiveRecord::Base.with_connection do
  41. World.find(rand1).attributes
  42. end
  43. json world
  44. end
  45. # Test type 3: Multiple database queries
  46. get '/queries' do
  47. worlds =
  48. ActiveRecord::Base.with_connection do
  49. ALL_IDS.sample(bounded_queries).map do |id|
  50. World.find(id).attributes
  51. end
  52. end
  53. json worlds
  54. end
  55. # Test type 4: Fortunes
  56. get '/fortunes' do
  57. @fortunes = ActiveRecord::Base.with_connection do
  58. Fortune.all
  59. end.to_a
  60. @fortunes << Fortune.new(
  61. id: 0,
  62. message: 'Additional fortune added at request time.'
  63. )
  64. @fortunes.sort_by!(&:message)
  65. erb :fortunes, layout: true
  66. end
  67. # Test type 5: Database updates
  68. get '/updates' do
  69. worlds = nil
  70. ActiveRecord::Base.with_connection do
  71. worlds = ALL_IDS.sample(bounded_queries).map do |id|
  72. world = World.find(id)
  73. new_value = rand1
  74. new_value = rand1 until new_value != world.randomNumber
  75. { id: id, randomNumber: new_value }
  76. end
  77. end
  78. worlds.sort_by!{_1[:id]}
  79. ActiveRecord::Base.with_connection do
  80. World.upsert_all(worlds)
  81. end
  82. json worlds
  83. end
  84. # Test type 6: Plaintext
  85. get '/plaintext' do
  86. content_type :text
  87. 'Hello, World!'
  88. end
  89. end