Joel
Joel

Reputation: 4603

How to call a method after creating a new instance of a class?

Im trying to call the send_text method from my sendtextcontroller:

require 'twilio-ruby'

class SendtextController < ApplicationController
  def index
  end


def send_text_message
     number_to_send_to = current_user.cell_phone

    account_sid = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    auth_token = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    twilio_phone_number = "(954)-333-3333"

       @client = Twilio::REST::Client.new account_sid, auth_token
    @twilio_client.account.sms.messages.create(
      :from => "+1#{twilio_phone_number}",
      :to => number_to_send_to
      :body => "Your bill has been added")
  end
end

In my Billscontroller after i create a new bill:

class BillsController < ApplicationController
  before_action :set_bill, only: [:show, :edit, :update, :destroy]


  def create
    @bill = Bill.new(bill_params)
    #sets new bill equal to the id of the current user signed in.
    @bill.user_id = current_user.id


    respond_to do |format|
      if @bill.save
        format.html { redirect_to @bill, notice: 'Bill was successfully created.' }
        format.json { render :show, status: :created, location: @bill }

      else
        format.html { render :new }
        format.json { render json: @bill.errors, status: :unprocessable_entity }
      end
    end
  end
end

Ive tried calling the send_text_message in many different places throughout the create method in the Billscontroller and have had no luck when i create a new bill on my localhost. Any suggestions? What am i doing wrong? Thanks in advance.

Upvotes: 1

Views: 323

Answers (1)

Devarsh Desai
Devarsh Desai

Reputation: 6112

Twilio has use cases where you want to create controllers to use their REST API. This is mainly beacuse of how the buisness logic is laid out in relation to their example applications. In this case, as long as you loaded the twilio gem, you can just create a helper method in your controller and invoke send_text_message from your BillsController. All the gem does is provide you with a wrapper so that you can perform a GET/POST requests to their servers.

Please let me know if you have any questions!

Upvotes: 2

Related Questions