Ich bin neu in Ruby und zu Rails. Ich verstehe nicht, warum das Folgende passiert. Ich verwende SendGrid zum Senden von E-Mails. Ich habe eine Klasse und eine Methode definiert:Objekt ist Null, wenn es als Instanzvariable initialisiert wird
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
Das funktioniert perfekt. Ich denke jedoch, es wäre besser, den Client nur einmal zu initialisieren, und nicht jedes Mal, wenn die Methode aufgerufen wird. Also habe ich es als Instanzvariable extrahiert.
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
Jetzt bekomme ich #<NoMethodError: undefined method 'client' for nil:NilClass>
. Durch Bebugging sehe ich, dass @send_grid
Null ist.
Ich rufe die Methode mit EmailService.new.send_email
. Nach meinem Verständnis ist @send_grid
eine Instanzvariable und sollte mit der Klasse initialisiert werden.
Warum passiert das?