Created
February 2, 2021 10:12
-
-
Save frangarcia/6e93c7c2403b3dde2cee56a37b910d9a to your computer and use it in GitHub Desktop.
Passing a closure as a binding property to generate an output string using string template engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Snippet to pass a method as a closure to generate an output string */ | |
import groovy.text.GStringTemplateEngine | |
import groovy.text.Template | |
import java.text.SimpleDateFormat | |
String formatDate(String date, String pattern, String timeZone){ | |
try { | |
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern) | |
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)) | |
return simpleDateFormat.format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(date)) | |
} catch (Exception e) { | |
println("Exception formatting the date ${date} using the pattern ${pattern} for timezone ${timeZone} - ${e}") | |
} | |
return date | |
} | |
GStringTemplateEngine engine = new GStringTemplateEngine() | |
List<Map> l = [ | |
["pattern":"ddMMyy","timezone":"Europe/London","expected":"2020-08-20T00:43:23Z:190820"], | |
["pattern":"ddMMyyHH","timezone":"Europe/Madrid","expected":"2020-08-20T00:43:23Z:20082000"], | |
["pattern":"ddMMyyHHmm","timezone":"America/New_York","expected":"2020-08-20T00:43:23Z:1908201843"], | |
] | |
l.each { Map m -> | |
String templateStr = '${params.date}:${formatDate.call(params.date, params.pattern, params.timezone)}' | |
Map binding = ["params":["date":"2020-08-20T00:43:23Z", "timezone":m.get("timezone"), "pattern":m.get("pattern")], "formatDate":this.&formatDate] | |
Map bindingDefaulted = binding?.findAll{it.value!=null}?.withDefault{ k -> defaultValue ?: '' } | |
Template template = engine.createTemplate(templateStr) | |
Writable result = template.make(bindingDefaulted) | |
assert result.toString() == m.get("expected") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment