[英]I am trying to use the twilio-ruby gem And I can get text messages to work from the Rails Console but In my controller I am a getting an error
[英]Can't call method from gem (Twilio-ruby), appears to be looking in my controller, how to scope this properly?
我的 gemfile 中有以下行并完成了bundle install
:
gem 'twilio-ruby'
我有以下基于 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
我得到的错误是:
uninitialized constant TwilioEntriesController::Twilio
Ruby 似乎在“TwilioEntriesController”中寻找“Twilio”类,这是调用的来源。 它应该从正确的类(“Twilio”)调用方法 - 给出了什么?
如何按照 twilio-ruby 文档中的描述调用 Twilio 类上的静态方法?
这绝对是由于没有正确需要 Twilio gem 造成的。 仔细检查bundle list
包含 twilio-ruby,并且 bundler 是否在您的 rails 应用程序中正确设置。
查找常量时,Ruby 将遍历Module.nesting
,在您的情况下为[TwilioEntriesController]
。 对于每个条目,它将搜索:
如果在任何地方都找不到该模块,则会引发异常,并在异常消息中使用它用于搜索的第一个模块。 所以你的错误也意味着顶层没有 Twilio 常量,可能是因为缺少对require
调用。
(Ruby 中没有静态方法这样的东西;只有实例方法和类方法——后者也可以被视为实例方法,这取决于您的观点。)
为时已晚,但最近遇到了同样的错误。 将此添加到您的文件中:
require 'rubygems'
require 'twilio-ruby'
在第 10 行尝试::Twilio
。
这就像从根 (/foo/bar) 为模块和类调用绝对路径。
我有一段时间没有构建 Rails 应用程序,但我认为您可以通过放置来解决这个问题
require 'twilio-ruby'
在控制器文件的顶部。 可能有一个更合适的中心位置可以将您的所有需求放在现代 Rails 应用程序中,因此请查阅文档以获取正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.