将变量传递给块 - Rails

时间:2015-12-28 15:19:59

标签: ruby-on-rails ruby

在我的rails应用中,我正在使用此gem与Gmail API进行互动:https://github.com/gmailgem/gmail

以下是我发送电子邮件的方法:

gmail = Gmail.connect(params[:email], params[:password])
@email = params[:email]

email = gmail.compose do
  to @email
  subject "Having fun in Puerto Rico!"
  body "Spent the day on the road..."
end
email.deliver!

我收到此错误:

An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.

电子邮件变量无法传递到块中。是什么造成的?如何传递动态电子邮件地址?

1 个答案:

答案 0 :(得分:7)

我确定这是因为@email是一个实例变量,绑定到self(有点等于self.email)。 gmail模块可以使用selfinstance_eval等所谓的“范围门”等方法轻松更改块内的class_eval。这是红宝石元编程的常规功能。

只需使用一个简单的变量,它就会被延续捕获。

email_to = params[:email]
email = gmail.compose do
    to email_to
    ...
end

我强烈建议不要将实例变量用作temp - 它们代表对象的状态。使用局部变量,这就是它们的设计目标。

相关问题