Mohammad Shahbaz
Mohammad Shahbaz

Reputation: 423

how to use a ruby rails variable in the curl (bash) script

I am trying to run this curl script in my ruby rails application:

%x{ curl -F token='08F14AE57696E458BA6FC6A203F57E69' -F overwriteBehavior=normal 
-F content=record -F type=flat -F format=json 
-F data='[{"record_id":"123","seat_id_seq":"bbb","address":"bbb","price":"bbb","email":"bbb","tickets1_complete":"2"}]'  
'https://cri-datacap.org/api/' }

and its working fine. Now I want don't want to hardcode the values so i am trying to give this values by the variable.

These variable contains value from the text field on my rails application:

%x{ curl -F token='08F14AE57696E458BA6FC6A203F57E69' -F overwriteBehavior=normal 
-F content=record -F type=flat -F format=json 
-F data='[{"record_id":"#{params[:record_id]}","seat_id_seq":"bbb","address":"bbb","price":"bbb","email":"bbb","tickets1_complete":"2"}]'  
'https://cri-datacap.org/api/' }

so I have tried for one variable record_id, but its not working.. This script is written in my controller.

Upvotes: 1

Views: 283

Answers (1)

tadman
tadman

Reputation: 211670

Ignoring the fact that using curl externally when libraries like curb exist, using %x{...} for this is extremely messy. What you want to do is call system:

data = [
  {
    record_id: params[:record_id],
    seat_id_seq: "bbb",
    address: "bbb",
    price: "bbb",
    email: "bbb",
    tickets1_complete: 2
  }
]

system(
  "curl",
  "-F", "overwriteBehavior=normal",
  "-F", "content=record",
  "-F", "type=flat",
  "-F", "format=json",
  "-F", "data=#{JSON.dump(data)}",
  'https://cri-datacap.org/api/'
)

When you're writing JSON data, do try and use JSON.dump or .to_json to ensure your document is 100% valid.

Upvotes: 3

Related Questions