JVK
JVK

Reputation: 3912

How to substitute variable in backtick command in ruby

I am trying to make a curl call in my rails application for sentimental analysis as shown here https://algorithmia.com/algorithms/nlp/SentimentAnalysis

text =   "I love coding"
secret = "yv5julwo8l7biwuni62r37t823igd87d97u623568yf"

result = `curl -X POST -d '"#{text}"' -H 'Content-Type: application/json' -H 'Authorization: Simple #{secret}' https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2`
result = JSON.parse(result)

But inside the back-tick, its not substituting the value correctly. So how to substitute the variable in this curl command?

When I execute this code with I love coding, I get response 0 while on their website, I get 2 ( that is correct), so that makes me believe its not substituting the variable value properly.

Upvotes: 1

Views: 2304

Answers (2)

Jordan Running
Jordan Running

Reputation: 106077

When making a system call with anything but the simplest arguments you should always use the Shellwords library to ensure that your arguments are properly escaped and/or quoted. For example:

require "shellwords"

text = '"I love coding"'
secret = "yv5julwo8l7biwuni62r37t823igd87d97u623568yf"

args = [ "-X", "POST",
         "-d", text,
         "-H", "Content-Type: application/json",
         "-H", "Authorization: Simple #{secret}",
         "https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2" ]

data = `curl #{args.shelljoin}`
result = JSON.parse(data)

And, as the Tin Man points out above, backticks are neither the only nor necessarily best way to make system calls in Ruby. I highly recommend reading this series of articles: https://devver.wordpress.com/2009/06/30/a-dozen-or-so-ways-to-start-sub-processes-in-ruby-part-1/

Lastly, making a system call to curl isn't generally the best way to make an HTTP request from Ruby when gems like rest-client, faraday and httparty are available, not to mention Net::HTTP in the standard library.

Upvotes: 2

Thomas Nys
Thomas Nys

Reputation: 359

I think there is an error in you api-key. Your code is working as is with my api-key.

Edit:

Code is working as is as shown in this:

enter image description here

Edit 2:

require 'json'

text =   'I love coding'
secret = 'secret'

result = `curl -X POST -d '"#{text}"' -H 'Content-Type: application/json' -H 'Authorization: Simple #{secret}' https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2`
result = JSON.parse(result)

puts result

Upvotes: 2

Related Questions