groovy closure parameters

Posted by Don on Stack Overflow See other posts from Stack Overflow or by Don
Published on 2009-05-18T01:41:06Z Indexed on 2010/04/28 0:43 UTC
Read the original article Hit count: 300

Filed under:
|

Hi,

The following example of using the sendMail method provided by the grails mail plugin appears in this book.

sendMail {
    to "[email protected]"
    subject "Registration Complete"
    body view:"/foo/bar", model:[user:new User()]
}

I understand that the code within {} is a closure that is passed to sendMail as a parameter. I also understand that to, subject and body are method calls.

I'm trying to figure out what the code that implements the sendMail method would look like, and my best guess is something like this:

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
    }
}

Is this reasonable, or am I missing something? In particular, are the methods invokedwithin the closure (to, subject, body), necessarily members of the same class as sendMail?

Thanks, Don

© Stack Overflow or respective owner

Related posts about groovy

Related posts about closures