0

Working on a Rails project that needs to send a link to a record to someone via SMS.

/services/twilio_client.rb:

def send_text(job, message)
    client = Twilio::REST::Client.new account_sid, auth_token
    client.messages.create(
    to: job.cell_number,
    from: phone_number,
    body: message
    )
end

From Controller:

    if job.save? 
        message = "#{@job.company} worker, you've got a new job.  See it here:"
        TwilioClient.new.send_text(@job, message)

In an ideal world, I could send them a link directly to the job via SMS, but Twilio won't accept ruby code as a media_url and dropping #{@job} in the message results in receiving the object #<Job:0x00007f0b60818338> in the SMS.

Clearly, this is a syntax issue, but try as I might I can't find a solution in the docs, the twilio-ruby gem, or examples published on the interweb.

PSCampbell
  • 858
  • 9
  • 27

1 Answers1

0

I would change the interface of the send_message a bit:

# in /services/twilio_client.rb:
def send_text(number, message)
  client = Twilio::REST::Client.new(account_sid, auth_token)
  client.messages.create(to: number, from: phone_number, body: message)
end

And then call it from the controller like this:

if job.save? 
  message = "#{@job.company} worker, you've got a new job.  See it here: #{media_url}"
  TwilioClient.new.send_text(@job.cell_number, message)
# ...

The important fact here is that URL builders are only available in controllers and views in Rails per default. When you need a URL in another object like a service model then the easiest way is to generate it on the controller level and pass it to the service.

spickermann
  • 100,941
  • 9
  • 101
  • 131