Sendgrid 实现 - 没有将 nil 隐式转换为 String

Sendgrid implementation - no implicit conversion of nil into String

我的环境是这样设置的:

echo "export SENDGRID_API_KEY='xxxxxxxxx'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

Sendgrid gem 已安装。

我尝试的代码 运行:

require 'sendgrid-ruby'
include SendGrid
require 'json'

def hello_world
  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)

  #previous version
  #sg = SendGrid::API.new(api_key: ENV['xxxxxxx'])

  #current version
  sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
  response = sg.client.mail._('send').post(request_body: mail.to_json)
  puts response.status_code
  puts response.body
  puts response.headers
end

hello_world

但我收到以下错误:

no implicit conversion of nil into String

此文件内:

/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in

我不知道这里出了什么问题....

完整错误:

/Users/pimzonneveld/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in `+': no implicit conversion of nil into String (TypeError)
    from /Users/pimzonneveld/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in `initialize'
    from app/helpers/mail.rb:12:in `new'
    from app/helpers/mail.rb:12:in `hello_world'
    from app/helpers/mail.rb:19:in `<main>'

您将环境变量 (xxxxxxxxx) 的值与其名称 (SENDGRID_API_KEY) 混淆了。

在代码中设置 API 键时,使用

  sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])

相反。

深说的对。 /ruby/gems/2.4.0/gems/sendgrid-ruby-5.2.0/lib/sendgrid/client.rb:24:in 指

"Authorization": "Bearer ' + @api_key + '",

因此,从 nil 到 String 的非隐式转换非常有意义。

你应该改变

sg = SendGrid::API.new(api_key: ENV['xxxxxxx'])

用于:

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])