【问题标题】:Under what file do you write twilio code in order to input instance variables?您在哪个文件下编写 twilio 代码以输入实例变量?
【发布时间】:2017-05-06 23:15:38
【问题描述】:

因此,我的应用程序的工作方式是用户输入一条消息,以及将消息发送到的电话号码。该应用程序使用 Twilio gem 发送消息。我试图弄清楚如何将从用户输入存储的变量调用到我的 twilio 代码中。

messages_controller.rb

class MessagesController < ApplicationController
  before_action :set_message, only: [:show, :edit, :update, :destroy]

  def index
    @message = Message.all
  end

  def show
  end

  def new
    @message = Message.new
  end

  def edit
  end

  def create
    @message = Message.create(message_params)
    @message.send_sms(message_params)
    if @message.save
      redirect_to @message
    else 
      flash[:alert] = "Contact not send message!"
    end
  end

  def update
      if @message.update(message_params)
        redirect_to @message
      else
        render :edit
      end
  end

  def destroy
    @message.destroy
    redirect_to messages_url
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_message
      @message = Message.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allowset_message         the white list through.
    def message_params
      params.require(:message).permit(:number, :text)
    end

end

twilio 代码

require 'twilio-ruby'

    def send_sms(text)
        account_sid = ENV["TWILIO_SID"] 
        auth_token = ENV["TWILIO_TOKEN"] 

        @client = Twilio::REST::Client.new account_sid, auth_token

        message = @client.account.messages.create(:body => @message.text,
         :to => @message.number,
         :from => ENV["FROM"]) 

         rescue Twilio::REST::RequestError => e
    end

【问题讨论】:

    标签: ruby-on-rails ruby controller twilio


    【解决方案1】:

    我建议将该代码拆分为不同的文件。

    让我们从您的控制器开始。您的 create 方法看起来像您想通过 Trello 发送消息,并且您也想将消息存储在您的数据库中。我会这样写控制器的创建方法:

    def create
      @message = Message.new(message_params)
      if @message.save_and_send         # Note the name of the method
        redirect_to @message
      else 
        flash[:alert] = "Contact not send message!"
        # render `new` again if this wasn't successful and 
        # show errors on the form (if exist).
        render :new             
      end
    end
    

    在下一步中,我在message.rb 中引入一个save_and_send 方法,该方法验证并发送消息,如果两者都成功则返回true

    def save_and_send
      save! if valid? && SmsGateway.send(self)
    end
    

    此方法首先验证记录。如果它是有效的,它会尝试发送消息。如果消息发送成功,它会使用save! 保存记录(因为此时它不应该失败)。

    我添加了新模型SmsGateway,因为恕我直言,将第三方代码封装到包装器中是一种很好的做法,因为这样可以更轻松地维护和将来更改 SMS 提供程序。 SmsGateway 类非常简单:

    # in app/models/sms_gateway.rb
    require 'twilio-ruby'
    
    class sms_gateway    
      def self.send(message)
        new.send(message)
      end
    
      def initialize
        @client = Twilio::REST::Client.new(ENV["TWILIO_SID"], ENV["TWILIO_TOKEN"])
      end
    
      def send(message)
        client.account.messages.create(
          body: message.text,
          to: message.number,
          from: ENV["FROM"])
        )
      rescue Twilio::REST::RequestError => e
        Rails.logger.error("SMS ERROR: #{e.message}")
        message.errors.add(:base, "Sending the message failed: #{e.message}")
        false
      end
    
    private
    
      attr_reader :client
    end
    

    SmsGateway 的救援块中,如果无法发送消息,我会向message 实例写入错误并返回false。这个false 确保在Message#save_and_send 中消息本身不存储在数据库中。并且我们能够向用户显示正确的错误消息。

    【讨论】:

    • 我按照您的建议实现了代码,并且在我修复它们时不断引发新的错误。例如,它引用 sms_gateway 中的私有方法“send”引发 noMethodError
    • 对不起,我写了我的答案,有可能对其进行测试。你是对的,save 方法不能是私有的。我更新了我的答案。
    • send 是您永远不想在 Ruby 中定义的方法。它用于将消息传递给对象,这些消息是您要调用的方法调用。我之前犯了定义send 的错误,它只是把事情搞砸了。我可以推荐方法名称deliver吗?
    【解决方案2】:

    如果有人好奇,答案是您将控制器中的方法放在私有下。你可以简单地调用它

    def create
        send_sms(message_params)
    end
    

    另外,方法中的参数也应该是 message_params。

    我做到了!!!!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      相关资源
      最近更新 更多