Skip to content

Instantly share code, notes, and snippets.

@dyong0
Created February 4, 2016 07:19
Show Gist options
  • Save dyong0/26ab45a9d90c89333edc to your computer and use it in GitHub Desktop.
Save dyong0/26ab45a9d90c89333edc to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class TemplateEvaluator {
private Map<String, Supplier<String>> keywords = new HashMap<>();
public void addTemplateVariable(String keyword, Supplier<String> template) {
keywords.put(keyword, template);
}
public String evaluteTemplate(String template) {
StringBuilder sbTemplate = new StringBuilder();
int prevIndex = 0;
int index = nextIndex(prevIndex, template);
while (index > -1) {
sbTemplate.append(template.substring(0, index));
template = template.substring(index);
index = template.indexOf("}");
String keyword = template.substring(2, index);
sbTemplate.append(keywords.get(keyword).get());
template = template.substring(index + 1);
index = template.indexOf("${");
}
sbTemplate.append(template);
return sbTemplate.toString();
}
private int nextIndex(int index, String template) {
return template.indexOf("${", index);
}
}
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
public class TemplateEvaluatorTest {
private TemplateEvaluator evaluator;
@Before
public void setup(){
evaluator = new TemplateEvaluator();
evaluator.addTemplateVariable("today", () -> LocalDate.now().toString());
evaluator.addTemplateVariable("year", () -> String.valueOf(LocalDate.now().getYear()));
evaluator.addTemplateVariable("month", () -> String.valueOf(LocalDate.now().getMonthValue() + 1));
evaluator.addTemplateVariable("day", () -> String.valueOf(LocalDate.now().getDayOfMonth()));
}
@Test
public void testTemplate(){
assertEquals(evaluator.evaluteTemplate("<html>${today}</html>"), "<html>" + LocalDate.now().toString() + "</html>");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment