Twilio の従業員です。この最初の質問が投稿されて以来、Rails には多くの変更が加えられています。Rails 4、Concerns、および Twilio Ruby gem を使用して、この問題にどのように対処できるかを共有したいと思います。
以下のコード サンプルでは、コントローラーを定義し、/controllers/voice_controller.rbWebhookable という名前の懸念を含めます。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
懸念自体は存在し/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
最後に、reminderTwilio 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