[英]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: 我正在使用Mail gem,并具有以下代码:
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. 我无法从Mail.default do
访问变量,我想这将是一个类问题。
It's probable that the block Mail
is given is executed in another context and the variables are not available in that scope. 给定Mail
块的可能性很可能在另一个上下文中执行,并且变量在该范围内不可用。 This sometimes happens in certain "Domain Specific Languages" (DSLs) written in Ruby. 有时这会发生在以Ruby编写的某些“域特定语言”(DSL)中。
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. 如果有的话,可以使用mattr_accessor
轻松创建这些模块。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.