-2

I'm using ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux] rails: Rails 5.1.3

I have action in which I check a phone number if it is valid or not and action where I send message. the message action working perfectly but I get an error when I try to check a number. this is the action

def check_phone_number
    account_sid = Rails.application.secrets.twilio_sid
    auth_token = Rails.application.secrets.twilio_token
    @lookup_client = Twilio::REST::LookupsClient.new(account_sid, 
                     auth_token)
    response = @lookup_client.phone_numbers.get("#
               {params[:phone_number]}")
    begin
      response.phone_number
      render json: {'response' => 'ok'}
    rescue Exception => e
      if e.code == 20404
        render json: { 'error' => 'Invalid Number' }
      else
        render json: { 'error' => 'Invalid Number' }
      end
    end
  end

the error is uninitialised Twilio::REST::LookupsClient

how can I solve it?

Jasjeet Singh
  • 332
  • 1
  • 6
  • 18

2 Answers2

3

Twilio developer evangelist here.

It looks like you have installed the latest version of the Twilio gem. In this version there is no longer a Twilio::REST::LookupsClient all REST clients are part of the Twilio::REST::Client object. You also can make the request specifically, rather than having to call on a property of the phone number object you create.

Check out the documentation and examples of making calls to the Lookup API with Ruby.

For right now, your code should look like this:

def check_phone_number
  account_sid = Rails.application.secrets.twilio_sid
  auth_token = Rails.application.secrets.twilio_token
  @lookup_client = Twilio::REST::Client.new(account_sid, auth_token)
  phone_number = @lookup_client.lookups.phone_numbers(params[:phone_number])

  begin
    response = phone_number.fetch
    render json: {'response' => 'ok'}
  rescue Twilio::REST::RestError => e
    if e.code == 20404
      render json: { 'error' => 'Invalid Number' }
    else
      render json: { 'error' => 'Invalid Number' }
    end
  end
end

Note, I also replaced your rescue Exception because it's a bad idea. Instead, you can rescue Twilio::REST::RestError.

For more on using the lookups API to validate phone numbers in Ruby, check out my blog post on using Active Model Validations and Twilio Lookups

philnash
  • 70,667
  • 10
  • 60
  • 88
0

Could be the first :: throwing it off. Try:

@lookup_client = Twilio::REST::LookupsClient.new(account_sid, 
                     auth_token)

instead of

@lookup_client = ::Twilio::Rest::Client.new account_sid, account_auth_token

Examples: https://github.com/twilio/twilio-ruby/blob/master/examples/examples.rb

Also, see https://github.com/twilio/twilio-ruby/blob/master/lib/twilio-ruby/rest/client.rb - looks like REST should be capitalized.

Ronak Bhatt
  • 162
  • 1
  • 15