Katie H Katie H - 4 years ago 215
Ruby Question

Passing variable into block - Rails

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..."

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?

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download