功能实现

时间:2018-12-26 15:39:58

标签: groovy

我已经实现了多种用于发送不同通知的常规方法,但是代码破坏了功能概念。因此,我想将所有常规方法重写/合并为一个方法,这样我就可以在需要的地方调用该方法。

成功与失败无关紧要,我需要将消息作为参数传递。

static void sendSuccessApplicationNotification(p1,p2,p3,p4) {
    def x = Notify(this)
    x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p3}")
    x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p4")
}

最后将以上内容转换为一种方法。检查了很多文章,但没有确切的例子。

1 个答案:

答案 0 :(得分:0)

您可以在通用函数中使用groovy模板引擎:

import groovy.text.SimpleTemplateEngine

void triggerBuild(a,b){
    println "${a} >>>> ${b}"
}

void sendNotification(code, Map parms, List nodes) {
    def templates = [
        'appY': 'SUCCESSFUL, application ${app}:${ver} started properly',
        'appN': 'FAILED, application ${app}:${ver} failed to start properly',
        'depY': 'SUCCESSFUL deployment of ${app}:${ver} to ${node}<br>Executed by ${user}',
        'depN': 'FAILED deployment of ${app}:${ver} to ${node}<br>Executed by ${user}'
    ]
    def template = templates[code]
    assert template
    def message = new SimpleTemplateEngine().createTemplate(template).make(parms).toString()
    nodes.each{node->
        triggerBuild(message, node)
    }
}

sendNotification('appY',[app:'myapp', ver:'v123'],['n1','n2'])

上面的代码将输出:

SUCCESSFUL, application myapp:v123 started properly >>>> n1
SUCCESSFUL, application myapp:v123 started properly >>>> n2