hello_world.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. Random.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. # Test type 1: JSON serialization
  36. get '/json' do
  37. json :message=>'Hello, World!'
  38. end
  39. # Test type 2: Single database query
  40. get '/db' do
  41. world = ActiveRecord::Base.connection_pool.with_connection do
  42. World.find(rand1).attributes
  43. end
  44. json world
  45. end
  46. # Test type 3: Multiple database queries
  47. get '/queries' do
  48. worlds = ActiveRecord::Base.connection_pool.with_connection do
  49. Array.new(bounded_queries) { World.find(rand1).attributes }
  50. end
  51. json worlds
  52. end
  53. # Test type 4: Fortunes
  54. get '/fortunes' do
  55. @fortunes = ActiveRecord::Base.connection_pool.with_connection do
  56. Fortune.all.to_a
  57. end
  58. @fortunes << Fortune.new(
  59. :id=>0,
  60. :message=>'Additional fortune added at request time.'
  61. )
  62. @fortunes.sort_by!(&:message)
  63. erb :fortunes, :layout=>true
  64. end
  65. # Test type 5: Database updates
  66. get '/updates' do
  67. worlds = ActiveRecord::Base.connection_pool.with_connection do |conn|
  68. Array.new(bounded_queries) do
  69. world = World.find(rand1)
  70. world.update(:randomnumber=>rand1)
  71. world.attributes
  72. end
  73. end
  74. json worlds
  75. end
  76. # Test type 6: Plaintext
  77. get '/plaintext' do
  78. content_type :text
  79. 'Hello, World!'
  80. end
  81. end