Tronathan
Tronathan

Reputation: 6794

Can't call method from gem (Twilio-ruby), appears to be looking in my controller, how to scope this properly?

I have the following line in my gemfile and have done a bundle install:

gem 'twilio-ruby'

I have the following code based on the examples for twilio-ruby gem:

class TwilioEntriesController < ApplicationController

  def process_message

    # init client 
    @account_sid = 'REMOVED'
    @auth_token = 'REMOVED'
    @from_number = '+14159675278'

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

    # send response
    @client.account.sms.messages.create(
      :from => @from_number,
      :to => '+REMOVED',
      :body => 'Hey there!'
    )

    render :result, :layout => ''
  end  

end

The error I am getting is:

uninitialized constant TwilioEntriesController::Twilio

It appears that Ruby is looking for the "Twilio" class inside of the "TwilioEntriesController", which is where the call is originating from. It should be calling the method from the correct class ("Twilio") - What gives?

How can I call static methods on the Twilio class as described by the twilio-ruby documentation?

Upvotes: 2

Views: 3462

Answers (5)

MAK
MAK

Reputation: 153

It's too late but ran into same error recently. Add this to your file:

require 'rubygems'
require 'twilio-ruby'

Upvotes: 0

amb
amb

Reputation: 499

I haven't built a Rails app in awhile but I think you can solve this problem by putting

require 'twilio-ruby'

at the top of your controller file. There may be a more appropriate central place to put all your requires in a modern Rails app though so consult documentation for the proper way.

Upvotes: 0

Mon ou&#239;e
Mon ou&#239;e

Reputation: 958

When a constant is looked up, Ruby will walk Module.nesting, which is [TwilioEntriesController] in your case. For each entry, it will search:

  1. In the module itself
  2. In the modules included in that entry (going recursively)
  3. For classes, in the superclass (also going recursively)

If the module can't be found anywhere, an exception is raised, and the first module it used to search is used in the exception message. So your error also means that there is no Twilio constant at top-level, probably because of a missing call to require.

(There's no such thing as a static method in Ruby; there are only instance and class methods — the latter of which can be seen as instance methods too, depending on your point of view.)

Upvotes: 1

Matt Gauger
Matt Gauger

Reputation: 1

Try ::Twilio on line 10.

That's like calling an absolute path from root (/foo/bar) for Modules & Classes.

Upvotes: 0

Max Chernyak
Max Chernyak

Reputation: 37367

This is most definitely caused by Twilio gem not being required properly. Double-check that bundle list includes twilio-ruby, and that bundler is properly setup in your rails app.

Upvotes: 2

Related Questions