hello_world.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. return QUERIES_MIN if queries < QUERIES_MIN
  17. return QUERIES_MAX if queries > QUERIES_MAX
  18. queries
  19. end
  20. def json(data)
  21. content_type :json
  22. JSON.fast_generate(data)
  23. end
  24. # Return a random number between 1 and MAX_PK
  25. def rand1
  26. rand(MAX_PK).succ
  27. end
  28. end
  29. after do
  30. response['Date'] = Time.now.httpdate
  31. end
  32. after do
  33. response['Server'] = SERVER_STRING
  34. end if SERVER_STRING
  35. after do
  36. ActiveRecord::Base.clear_active_connections!
  37. end
  38. # Test type 1: JSON serialization
  39. get '/json' do
  40. json :message=>'Hello, World!'
  41. end
  42. # Test type 2: Single database query
  43. get '/db' do
  44. world =
  45. ActiveRecord::Base.connection_pool.with_connection do
  46. World.find(rand1).attributes
  47. end
  48. json world
  49. end
  50. # Test type 3: Multiple database queries
  51. get '/queries' do
  52. worlds =
  53. ActiveRecord::Base.connection_pool.with_connection do
  54. Array.new(bounded_queries) do
  55. World.find(rand1)
  56. end
  57. end
  58. json worlds.map!(&:attributes)
  59. end
  60. # Test type 4: Fortunes
  61. get '/fortunes' do
  62. @fortunes = ActiveRecord::Base.connection_pool.with_connection do
  63. Fortune.all
  64. end.to_a
  65. @fortunes << Fortune.new(
  66. :id=>0,
  67. :message=>'Additional fortune added at request time.'
  68. )
  69. @fortunes.sort_by!(&:message)
  70. erb :fortunes, :layout=>true
  71. end
  72. # Test type 5: Database updates
  73. get '/updates' do
  74. worlds =
  75. ActiveRecord::Base.connection_pool.with_connection do
  76. Array.new(bounded_queries) do
  77. world = World.find(rand1)
  78. new_value = rand1
  79. new_value = rand1 while new_value == world.randomnumber
  80. world.update(randomnumber: new_value)
  81. world
  82. end
  83. end
  84. json worlds.map!(&:attributes)
  85. end
  86. # Test type 6: Plaintext
  87. get '/plaintext' do
  88. content_type :text
  89. 'Hello, World!'
  90. end
  91. end