简体   繁体   中英

how to connect to Twilio API with ruby

Sorry this is a very basic question so it should be easy to answer!

Using ruby and sinatra, I am trying to connect, via the api, to get details of my calls. The prescribed way to do this by twilio seems to be:

@client = Twilio::REST::Client.new account_sid, auth_token
# Loop over calls and print out a property for each one
@client.account.calls.list.each do |call|
puts call.sid
puts call.from
puts call.to

which works fine and "puts" the data in the terminal. I want to print the results on an HTML page, so I changed the line

@client.account.calls.list.each do |call|

to

@calls = @client.account.calls.list

and removed the last 3 lines of the code block above, ie. all the "puts"

then, attempting to print on my index page I included the following:

<% @calls.each do |call| %>
 <h4 style="color: #ff0000;"><%= params['msg'] %></h4>
 <ul>
  <li> <%= call.from %> </li>
  <li> <%= call.to %> </li>
  </ul>
<% end %>

The error message says:

undefined method `each' for nil:NilClass

so I am not connecting to twilio it seems even though the code is almost exactly the same as that above which does connect and produce the required results.

Any ideas? All help gratefully received.

In Sinatra, do not use instance variables to store connection objects and similar stuff. Instead of @call , use the set method that enables a user to set such objects to different variables.

The calls.list method, as per the code, is defined in the Twilio::REST::ListResource module. This returns an array and so, the second part of your code (in the index.erb ) is correct.

The problem is, when you start using instance variables for storing the connection object, it gets reset in the route and that's what's happening inside the get do .. end block.

Change the code to:

set :client, Twilio::REST::Client.new(account_sid, account_pass)
# Now, this setting can be accessed by settings.client

get '/calls' do
  @calls = settings.client.account.calls
  erb :index
end

# index.erb

<% @calls.each do |call| %>
...
<% end %>

This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM