Groovy closing options

The following example of using the sendMail method provided by the Grails mail plugin is presented in this book .

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

I understand that the code inside {} is a closure that is passed to sendMail as a parameter. I also understand that to, subjectand bodyare method calls.

I am trying to understand what the code that implements the sendMail method looks like, and as I understand it, it 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, methods caused by the closure of the ( to, subject, body) are necessarily members of the same class as that sendMail?

Thanks Don

+5
source share
2 answers

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[])
    }
}
+7

, sendMail, , . sendMail , , , , builder, . , , , .

, , , , , - , ​​ , . , to(), to MailService, .

, .

// 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
}
+1

All Articles