Skip to content

Commit 1a9db10

Browse files
authored
Add check() method for Template.
1 parent c291dc1 commit 1a9db10

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

src/main/java/com/github/underscore/$.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,33 @@ public String apply(Map<K, V> value) {
129129
}
130130
return result;
131131
}
132+
133+
@Override
134+
public List<String> check(Map<K, V> value) {
135+
final String evaluate = TEMPLATE_SETTINGS.get("evaluate");
136+
final String interpolate = TEMPLATE_SETTINGS.get("interpolate");
137+
final String escape = TEMPLATE_SETTINGS.get("escape");
138+
String result = template;
139+
final List<String> notFound = new ArrayList<String>();
140+
for (final Map.Entry<K, V> element : value.entrySet()) {
141+
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(interpolate.replace(ALL_SYMBOLS,
142+
"\\s*\\Q" + ((Map.Entry) element).getKey() + "\\E\\s*")).matcher(result);
143+
boolean isFound = matcher.find();
144+
result = matcher.replaceAll(String.valueOf(((Map.Entry) element).getValue()));
145+
matcher = java.util.regex.Pattern.compile(escape.replace(ALL_SYMBOLS,
146+
"\\s*\\Q" + ((Map.Entry) element).getKey() + "\\E\\s*")).matcher(result);
147+
isFound |= matcher.find();
148+
result = matcher.replaceAll(escape(String.valueOf(((Map.Entry) element).getValue())));
149+
matcher = java.util.regex.Pattern.compile(evaluate.replace(ALL_SYMBOLS,
150+
"\\s*\\Q" + ((Map.Entry) element).getKey() + "\\E\\s*")).matcher(result);
151+
isFound |= matcher.find();
152+
result = matcher.replaceAll(String.valueOf(((Map.Entry) element).getValue()));
153+
if (!isFound) {
154+
notFound.add("" + ((Map.Entry) element).getKey());
155+
}
156+
}
157+
return notFound;
158+
}
132159
}
133160

134161
private static final class MyIterable<T> implements Iterable<T> {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
package com.github.underscore;
22

3+
import java.util.List;
4+
35
public interface Template<T> extends Function1<T, String> {
6+
List<String> check(T arg);
47
}

src/test/java/com/github/underscore/UtilityTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,14 @@ public void templateValue3() {
258258
put("name", "moe"); put("value", "<script>"); } }));
259259
}
260260

261+
@Test
262+
public void templateCheck() {
263+
Template<Map<String, Object>> compiled = $.template("hello: <%= name %>");
264+
assertTrue(compiled.check(new LinkedHashMap<String, Object>() { {
265+
put("name", "moe"); } }).isEmpty());
266+
assertEquals("name2", compiled.check(new LinkedHashMap<String, Object>() { {
267+
put("name2", "moe"); } }).get(0));
268+
}
261269
/*
262270
var fortmatted = _.format("hello: {}", "moe");
263271
=> "hello: moe"

0 commit comments

Comments
 (0)