【问题标题】:Object is nil when initialized as instance variable初始化为实例变量时对象为零
【发布时间】:2017-11-16 19:21:40
【问题描述】:

我是 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 是一个实例变量,应该使用类进行初始化。

为什么会这样?

【问题讨论】:

    标签: ruby-on-rails ruby initialization instance-variables


    【解决方案1】:

    把它放在构造函数中。在您的 sn-p 中执行该赋值表达式,但在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 2013-11-10
      • 2011-12-25
      相关资源
      最近更新 更多