【问题标题】:Rails 3 XML Builder / Twilio APIRails 3 XML 生成器/Twilio API
【发布时间】:2011-04-22 01:45:36
【问题描述】:

此 Twilio API 示例代码在 Rails 3 中不起作用:

#voice_controller.rb

  def reminder
    @postto = BASE_URL + '/directions'

    respond_to do |format|
      format.xml { @postto }
    end
  end

#reminder.xml.builder

xml.instruct!
xml.Response do
xml.Gather(:action => @postto, :numDigits => 1) do
    xml.Say "Hello this is a call from Twilio.  You have an appointment 
        tomorrow at 9 AM."
    xml.Say "Please press 1 to repeat this menu. Press 2 for directions.
        Or press 3 if you are done."
    end
end

有什么想法吗?

Twilio 似乎成功拨打了电话(我可以看到带有我的电话号码、位置等的参数),但随后返回了这个模糊的响应代码:

Completed 406 Not Acceptable in 0ms

【问题讨论】:

  • 你把 XML builder 文件放在哪里???

标签: ruby-on-rails ruby xml ruby-on-rails-3 twilio


【解决方案1】:

Twilio 不会在 its requests 中发送 Accept HTTP 标头,这会导致 Rails 3 决定它无法使用适当的内容类型进行响应。我认为以下内容会为您解决这个问题:

#voice_controller.rb 默认提醒 @postto = BASE_URL + '/directions' 渲染:content_type => '应用程序/xml' 结尾

【讨论】:

    【解决方案2】:

    这里是 Twilio 员工。自从发布这个原始问题以来,Rails 发生了很多变化,我想分享您如何使用 Rails 4、Concerns 和 Twilio Ruby gem 来解决这个问题。

    在下面的代码示例中,我在 /controllers/voice_controller.rb 中定义了控制器,并包含了一个名为 Webhookable 的关注点。 Webhookable Concern 让我们可以将与 Twilio webhook 相关的逻辑(将 HTTP 响应标头设置为 text/xml、呈现 TwiML、验证请求来自 Twilio 等)封装到单个模块中。

    require 'twilio-ruby'
    
    class VoiceController < ApplicationController
      include Webhookable
    
      after_filter :set_header
    
      # controller code here
    
    end
    

    Concern 本身位于/controllers/concerns/webhookable.rb,并且相当简单。现在,它只是将所有操作的 Content-Type 设置为 text/xml,并提供一种方法来呈现 TwiML 对象。我没有包含验证请求是否来自 Twilio 的代码,但这很容易添加:

    module Webhookable
        extend ActiveSupport::Concern
    
        def set_header
          response.headers["Content-Type"] = "text/xml"
        end
    
        def render_twiml(response)
          render text: response.text
        end
    
    end
    

    最后,您的 reminder 操作可能看起来像使用 Twilio gem 生成 TwiML 并使用 Concern 将此对象呈现为文本:

      def reminder
        response = Twilio::TwiML::Response.new do |r|
          r.Gather :action => BASE_URL + '/directions', :numDigits => 1 do |g|
            g.Say 'Hello this is a call from Twilio.  You have an appointment 
        tomorrow at 9 AM.'
            g.Say 'Please press 1 to repeat this menu. Press 2 for directions.
        Or press 3 if you are done.'
          end
        end
    
        render_twiml response
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      相关资源
      最近更新 更多