Browse Source

[ruby/rack-sequel] Use constants for HTTP headers (#8957)

Constants improve performance as these string don't need to be allocated
again after each request.
Petrik de Heus 1 year ago
parent
commit
444fb65a2d
2 changed files with 15 additions and 9 deletions
  1. 6 0
      frameworks/Ruby/rack-sequel/boot.rb
  2. 9 9
      frameworks/Ruby/rack-sequel/hello_world.rb

+ 6 - 0
frameworks/Ruby/rack-sequel/boot.rb

@@ -6,6 +6,12 @@ MAX_PK = 10_000
 QUERIES_MIN = 1
 QUERIES_MAX = 500
 SEQUEL_NO_ASSOCIATIONS = true
+CONTENT_TYPE = 'Content-Type'
+JSON_TYPE = 'application/json'
+HTML_TYPE = 'text/html; charset=utf-8'
+PLAINTEXT_TYPE = 'text/plain'
+DATE_HEADER = 'Date'
+SERVER_HEADER = 'Server'
 
 SERVER_STRING =
   if defined?(PhusionPassenger)

+ 9 - 9
frameworks/Ruby/rack-sequel/hello_world.rb

@@ -3,7 +3,7 @@
 # Our Rack application to be executed by rackup
 class HelloWorld
   DEFAULT_HEADERS = {}.tap do |h|
-    h['Server'] = SERVER_STRING if SERVER_STRING
+    h[SERVER_HEADER] = SERVER_STRING if SERVER_STRING
 
     h.freeze
   end
@@ -91,29 +91,29 @@ class HelloWorld
       case env['PATH_INFO']
       when '/json'
         # Test type 1: JSON serialization
-        ['application/json', JSON.fast_generate(:message=>'Hello, World!')]
+        [JSON_TYPE, JSON.fast_generate(:message=>'Hello, World!')]
       when '/db'
         # Test type 2: Single database query
-        ['application/json', JSON.fast_generate(db)]
+        [JSON_TYPE, JSON.fast_generate(db)]
       when '/queries'
         # Test type 3: Multiple database queries
-        ['application/json', JSON.fast_generate(queries(env))]
+        [JSON_TYPE, JSON.fast_generate(queries(env))]
       when '/fortunes'
         # Test type 4: Fortunes
-        ['text/html; charset=utf-8', fortunes]
+        [HTML_TYPE, fortunes]
       when '/updates'
         # Test type 5: Database updates
-        ['application/json', JSON.fast_generate(updates(env))]
+        [JSON_TYPE, JSON.fast_generate(updates(env))]
       when '/plaintext'
         # Test type 6: Plaintext
-        ['text/plain', 'Hello, World!']
+        [PLAINTEXT_TYPE, 'Hello, World!']
       end
 
     [
       200,
       DEFAULT_HEADERS.merge(
-        'Content-Type'=>content_type,
-        'Date'=>Time.now.httpdate
+        CONTENT_TYPE => content_type,
+        DATE_HEADER => Time.now.httpdate
       ),
       body
     ]