How to connect to Twilio API with ruby

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

Using ruby ​​and sinatra, I try to connect via api to get detailed information about my calls. The prescribed way to do this twilio is as follows:

@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 great and puts data into 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 deleted the last 3 lines of code above, i.e. puts everything

then, trying 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 

therefore, I do not connect to twilio, it seems, even if the code is almost the same as above, which binds and creates the required results.

Any ideas? All help was gratefully received.

+4
source share
1 answer

In Sinatra, do not use instance variables to store connection objects and similar materials. Instead of @call use the set method, which allows the user to set such objects for different variables.

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

The problem is that when you start using instance variables to store the connection object, it gets reset in the route and what happens 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 %> 

That should work.

0
source

Source: https://habr.com/ru/post/1481700/


All Articles