Browse Source

[rails] Return plain json from route (#9573)

Return JSON from the routes is a lot faster:

+------------+------------------------------+------+
|        name|                   branch_name|  json|
+------------+------------------------------+------+
|rails-iodine|                        master|105369|
|rails-iodine|         rails/json-from-route|144006|
+------------+------------------------------+------+
Petrik de Heus 5 months ago
parent
commit
8ff228e928

+ 0 - 8
frameworks/Ruby/rails/app/controllers/application_controller_metal.rb

@@ -1,8 +0,0 @@
-# frozen_string_literal: true
-
-class ApplicationControllerMetal < ActionController::Metal
-  def add_headers
-    response.set_header('Server', 'rails')
-    response.set_header('Date', Time.now.httpdate)
-  end
-end

+ 0 - 9
frameworks/Ruby/rails/app/controllers/json_controller.rb

@@ -1,9 +0,0 @@
-# frozen_string_literal: true
-
-class JsonController < ApplicationControllerMetal
-  def index
-    add_headers
-    self.content_type = 'application/json'
-    self.response_body = { 'message' => 'Hello, World!' }.to_json
-  end
-end

+ 44 - 10
frameworks/Ruby/rails/config/routes.rb

@@ -1,19 +1,53 @@
 Rails.application.routes.draw do
   # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
 
-  get "json", to: JsonController.action(:index)
+  JsonApp = if defined?(Falcon) || defined?(Puma) || defined?(Agoo)
+    ->(env) do
+      [200,
+       {
+         'Server' => 'Rails',
+         'Content-Type' => 'application/json',
+         'Date' => Time.now.httpdate,
+       },
+       [{ 'message' => 'Hello, World!' }.to_json]]
+    end
+  else
+    ->(env) do
+      [200,
+       {
+         'Server' => 'Rails',
+         'Content-Type' => 'application/json'
+       },
+       [{ 'message' => 'Hello, World!' }.to_json]]
+    end
+  end
+
+  PlaintextApp = if defined?(Falcon) || defined?(Puma) || defined?(Agoo)
+    ->(env) do
+      [200,
+       {
+         'Server' => 'Rails',
+         'Content-Type' => 'text/plain',
+         'Date' => Time.now.httpdate
+       },
+       ['Hello, World!']]
+    end
+  else
+    ->(env) do
+      [200,
+       {
+         'Server' => 'Rails',
+         'Content-Type' => 'text/plain'
+       },
+       ['Hello, World!']]
+    end
+  end
+
+  get "json", to: JsonApp
   get "db", to: "hello_world#db"
   get "queries", to: "hello_world#query"
   get "fortunes", to: "hello_world#fortune"
   get "updates", to: "hello_world#update"
-  get "plaintext", to: ->(env) do
-    [200,
-     {
-       'Content-Type' => 'text/plain',
-       'Date' => Time.now.httpdate,
-       'Server' => 'Rails'
-     },
-     ['Hello, World!']]
-  end
+  get "plaintext", to: PlaintextApp
   get "cached", to: "hello_world#cached_query"
 end