5

本书中出现了以下使用 grails 邮件插件提供的 sendMail 方法的示例。

sendMail {
    to "foo@example.org"
    subject "Registration Complete"
    body view:"/foo/bar", model:[user:new User()]
}

我知道 {} 中的代码是一个作为参数传递给 sendMail 的闭包。我也明白tosubject并且body是方法调用。

我试图弄清楚实现 sendMail 方法的代码是什么样的,我最好的猜测是这样的:

MailService {

    String subject
    String recipient
    String view
    def model

    sendMail(closure) {
        closure.call()
        // Code to send the mail now that all the 
        // various properties have been set
    }

    to(recipient) {
        this.recipient = recipient
    }

    subject(subject) {
        this.subject = subject;
    }

    body(view, model) {
        this.view = view
        this.model = model
    }
}

这是合理的,还是我错过了什么?特别是,闭包(to, subject, body)中调用的方法是否必须与 ? 属于同一类的成员sendMail

谢谢,唐

4

2 回答 2

7

MailService.sendMail 闭包委托:

 MailMessage sendMail(Closure callable) {
    def messageBuilder = new MailMessageBuilder(this, mailSender)
    callable.delegate = messageBuilder
    callable.resolveStrategy = Closure.DELEGATE_FIRST
    callable.call()

    def message = messageBuilder.createMessage()
    initMessage(message)
    sendMail message
    return message
}

例如,MailMessageBuilder 的方法:

void to(recip) {
    if(recip) {
        if (ConfigurationHolder.config.grails.mail.overrideAddress)
            recip = ConfigurationHolder.config.grails.mail.overrideAddress
        getMessage().setTo([recip.toString()] as String[])
    }
}
于 2010-04-28T00:39:30.987 回答
1

我不确定 sendMail 方法的确切作用,因为我没有您提到的书。如您所描述的, sendMail 方法确实采用了闭包,但它可能使用构建器而不是以正常方式执行。本质上,这将是一种用于描述要发送的电子邮件的领域特定语言。

您定义的类不起作用的原因是闭包的范围是声明它的地方而不是运行它的地方。因此,让您的闭包调用 to() 方法,除非您将邮件服务的实例传递给闭包,否则它将无法调用 MailService 中的 to 方法。

通过一些修改,您的示例可以通过使用常规闭包来工作。以下对调用的更改和

// The it-> can be omitted but I put it in here so you can see the parameter
service.sendMail {it->
    it.to "foo@example.org"
    it.subject "Registration Complete"
    it.body view:"/foo/bar", model:[user:new User()]
}

类中的 sendMail 方法应如下所示

def sendMail(closure) {
    closure(this)
    // Code to send the mail now that all the 
    // various properties have been set
}
于 2009-05-18T02:06:27.793 回答