0
我是Ruby新手,還有Rails。我不明白爲什麼會發生下列情況。我正在使用SendGrid發送電子郵件。我已經定義了一個類和一個方法:當初始化爲實例變量時,對象爲零
class EmailService
include SendGrid
def send_email
from = Email.new(email: '[email protected]')
to = Email.new(email: '[email protected]')
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: '[email protected]')
to = Email.new(email: '[email protected]')
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
是一個實例變量,應該用該類進行初始化。
爲什麼會發生這種情況?