我是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
是一个实例变量,应该用类初始化。
为什么会这样?
答案 0 :(得分:2)
将它放在构造函数中。在您的代码段中执行了分配表达式但在send_email
方法中没有的另一个范围
class EmailService
include SendGrid
def initialize
@send_grid = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
end
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