简体   繁体   中英

Accessing variables from inside a block with Mail gem

I have a problem with accessing the content of some variables. I'm using the Mail gem and have the following code:

class Email
  attr_accessor :server, :port, :username, :password, :ssl

  def check_mail
    # puts server --->  imap.googlemail.com ---> work
    Mail.defaults do
      # puts server --->  nil ---> not work
      retriever_method :imap, address:     server, #---> obviously not work
                                 port:       port,
                            user_name:   username,
                             password:   password,
                           enable_ssl:    ssl
    end
  end
end

def account
 acc          = Email.new
 acc.server   = 'imap.googlemail.com'
 acc.port     = '993'
 acc.username = 'xxx'
 acc.password = 'xxx'
 acc.ssl      = 'true'

 acc.check_mail
end

I can not access the variables from within Mail.default do , I guess it will be a class problem.

It's probable that the block Mail is given is executed in another context and the variables are not available in that scope. This sometimes happens in certain "Domain Specific Languages" (DSLs) written in Ruby.

You'll need to bridge over whatever data you want to use. This would be possible if you create a namespace for your configuration:

 Mail.defaults do
   retriever_method :...,
     :address => MyModule.address,
     # ...
 end

Those modules can be easily created with mattr_accessor if you have that.

It might also be possible to use a sort of closure to achieve this:

this = self

Mail.defaults do
  retriever_method :...,
    :address => this.address,
    # ...
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM