2017-06-14 74 views
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是一個實例變量,應該用該類進行初始化。

爲什麼會發生這種情況?

回答

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: '[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