【问题标题】:Sendgrid implementation - no implicit conversion of nil into StringSendgrid 实现 - 没有将 nil 隐式转换为字符串
【发布时间】:2018-04-17 10:58:42
【问题描述】:

我的环境是这样设置的:

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

【问题讨论】:

  • this:ENV['xxxxxxx']的值可能是nil

标签: ruby-on-rails ruby email sendgrid sendgrid-rails


【解决方案1】:

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

在代码中设置 API 密钥时,请使用

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

改为。

【讨论】:

  • 我还有一个奇怪的问题。上面的代码放在 helpers/mail.rb 中,当从命令行执行时它可以工作。但是,当我将它放入控制器并尝试执行时,我仍然收到 no implicit conversion of nil into String 错误。您可能知道是什么原因造成的吗?
  • 在启动 rails 服务器(在同一个 shell 中)之前,您可能没有获取 env 文件。
  • 在完全重新启动服务器后,重新启动 sublime(.env 文件仍然存在正确的信息)并再次获取 env 文件以确保我仍然得到错误。我真的很奇怪 app/helper 中的 mail.rb 可以工作,但它在另一个控制器中中断了?
  • 你不需要重启你的编辑器。你是如何启动你的服务器的?试试这个:SENDGRID_API_KEY=xxxxxxxx rails s
  • 基本上,您必须确保 prod-server 也提供 env-variables。但那是一个不同的问题。在 engineyard.com/blog/encrypted-rails-secrets-on-rails-5.1 阅读 Rails 的秘密,在 digitalocean.com/community/tutorials/… 阅读环境变量。
【解决方案2】:

深是对的。 /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'])

【讨论】:

  • 我还有一个奇怪的问题。上面的代码放在 helpers/mail.rb 中,当从命令行执行时它可以工作。但是,当我将它放入控制器并尝试执行时,我仍然收到no implicit conversion of nil into String 错误。您可能知道是什么原因造成的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2019-08-25
  • 2019-03-11
  • 2023-04-09
相关资源
最近更新 更多