2017-06-14 5 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>が得られます。私はbebuuggingによって@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 
関連する問題