【发布时间】:2017-11-16 19:21:40
【问题描述】:
我是 Ruby 和 Rails 的新手。我无法理解为什么会发生以下情况。我正在使用 SendGrid 发送电子邮件。我已经定义了一个类和一个方法:
class EmailService
include SendGrid
def send_email
from = Email.new(email: 'test@example.com')
to = Email.new(email: 'test@example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
mail = Mail.new(from, subject, to, content)
response = sg.client.mail._('send').post(request_body: mail.to_json)
end
end
这非常有效。但是,我认为最好只初始化一次客户端,而不是每次调用该方法。所以我把它提取为一个实例变量。
class EmailService
include SendGrid
@send_grid = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
def send_email
from = Email.new(email: 'test@example.com')
to = Email.new(email: 'test@example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
mail = Mail.new(from, subject, to, content)
response = @send_grid.client.mail._('send').post(request_body: mail.to_json)
end
end
现在我得到#<NoMethodError: undefined method 'client' for nil:NilClass>。通过调试,我看到 @send_grid 为零。
我正在使用EmailService.new.send_email 调用该方法。据我了解,@send_grid 是一个实例变量,应该使用类进行初始化。
为什么会这样?
【问题讨论】:
标签: ruby-on-rails ruby initialization instance-variables