hello_world.rb 2.0 KB

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