【问题标题】:uninitialized Twilio::REST::LookupsClient未初始化的 Twilio::REST::LookupsClient
【发布时间】:2017-08-18 07:31:20
【问题描述】:

我正在使用ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux] 导轨:Rails 5.1.3

我有一个检查电话号码是否有效的操作以及我发送消息的操作。 消息操作完美运行,但当我尝试检查数字时出现错误。这是行动

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

错误是uninitialised Twilio::REST::LookupsClient

我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby twilio lookup


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    您似乎安装了最新版本的 Twilio gem。在此版本中不再有 Twilio::REST::LookupsClient 所有 REST 客户端都是 Twilio::REST::Client 对象的一部分。您也可以专门提出请求,而不必调用您创建的电话号码对象的属性。

    查看making calls to the Lookup API with Ruby 的文档和示例。

    目前,您的代码应如下所示:

    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
    

    注意,我还替换了您的rescue Exception,因为it's a bad idea。相反,您可以rescue Twilio::REST::RestError

    有关在 Ruby 中使用查找 API 验证电话号码的更多信息,请查看我在 using Active Model Validations and Twilio Lookups 上的博客文章

    【讨论】:

      【解决方案2】:

      可能是第一个 :: 扔掉它。试试:

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

      而不是

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

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

      另外,请参阅 https://github.com/twilio/twilio-ruby/blob/master/lib/twilio-ruby/rest/client.rb - 看起来 REST 应该大写。

      【讨论】:

      • 不!你甚至读过我的问题吗?我知道你从哪里复制它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      相关资源
      最近更新 更多