groovy闭包参数

Dón*_*nal 5 groovy closures

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

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

我理解{}中的代码是一个闭包,它作为参数传递给sendMail.我也明白to,subject并且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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是合理的,还是我错过了什么?具体地讲,是invokedwithin闭合(方法to,subject,body),必须是相同的类的成员作为sendMail

谢谢,唐

小智 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
}
Run Code Online (Sandbox Code Playgroud)

例如,MailMessageBuilder的方法:

void to(recip) {
    if(recip) {
        if (ConfigurationHolder.config.grails.mail.overrideAddress)
            recip = ConfigurationHolder.config.grails.mail.overrideAddress
        getMessage().setTo([recip.toString()] as String[])
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ail 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()]
}
Run Code Online (Sandbox Code Playgroud)

类中的 sendMail 方法应该如下所示

def sendMail(closure) {
    closure(this)
    // Code to send the mail now that all the 
    // various properties have been set
}
Run Code Online (Sandbox Code Playgroud)