Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable into block - Rails [duplicate]

Within my rails app, I am using this gem to interact with the Gmail API: https://github.com/gmailgem/gmail

Here is what I have in a method to send an email:

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!

I am getting this error:

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

The email variable is not able to pass into the block. What is causing this? How can I pass in a dynamic email address?

like image 851
Katie H Avatar asked Dec 28 '15 15:12

Katie H


1 Answers

I'm sure it happens because @email is an instance variable, binded to self (somewhat equal to self.email). And gmail module can easily change self inside block using methods like instance_eval or class_eval, so-called "scope gates". It's regular feature for ruby metaprogramming.

Just use a simple variable, it will be caught by continuation.

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

And I would strongly recommend not to use instance variables as temp - they represent state of object. Use local variables, that's what they are designed for.

like image 197
Meredian Avatar answered Sep 20 '22 05:09

Meredian