Don't repeat yourself.
authorBob Aman <bobaman@google.com>
Tue, 11 Oct 2011 21:00:57 +0000 (00:00 +0300)
committerBob Aman <bobaman@google.com>
Tue, 11 Oct 2011 21:00:57 +0000 (00:00 +0300)
examples/prediction/prediction.rb

index d1acb4c22e407b420f614fe1ef9142af3139e8da..c9d51bb6a9ed5c4de58d4771e18790a9ec75dd21 100644 (file)
@@ -120,6 +120,12 @@ get '/train' do
     :headers => {'Content-Type' => 'application/json'},
     :body_object => training
   )
+
+  return [
+    200,
+    [["Content-Type", "application/json"]],
+    ::JSON.generate({"status": "success"})
+  ]
 end
 
 get '/checkStatus' do
@@ -128,25 +134,10 @@ get '/checkStatus' do
     :parameters => {'id' => 'language-sample'}
   )
 
-  # Assemble some JSON our client-side code can work with.
-  json = {}
-  if result.status != 200
-    if result.data["error"]
-      message = result.data["error"]["errors"].first["message"]
-      json["message"] = "#{message} [#{result.status}]"
-    else
-      json["message"] = "Error. [#{result.status}]"
-    end
-    json["response"] = ::JSON.parse(result.body)
-    json["status"] = "error"
-  else
-    json["response"] = ::JSON.parse(result.body)
-    json["status"] = "success"
-  end
   return [
     200,
     [["Content-Type", "application/json"]],
-    ::JSON.generate(json)
+    assemble_json_body(result)
   ]
 end
 
@@ -160,6 +151,16 @@ post '/predict' do
     :headers => {'Content-Type' => 'application/json'},
     :body_object => input
   )
+
+  return [
+    200,
+    [["Content-Type", "application/json"]],
+    assemble_json_body(result)
+  ]
+end
+
+def assemble_json_body(result)
+  # Assemble some JSON our client-side code can work with.
   json = {}
   if result.status != 200
     if result.data["error"]
@@ -174,9 +175,5 @@ post '/predict' do
     json["response"] = ::JSON.parse(result.body)
     json["status"] = "success"
   end
-  return [
-    200,
-    [["Content-Type", "application/json"]],
-    ::JSON.generate(json)
-  ]
+  return ::JSON.generate(json)
 end