![]() |
|
Navigation |
Synopsis Using string templates to generate code.
Description Many websites and code generators use template-based code generation. They start from a text template that contains embedded variables and code. The template is "executed" by replacing the embedded variables and code by their string value. Languages like PHP and Ruby are popular for this feature. Let's see how we can do this in Rascal.
Rascal provides string templates that rival what is provided in Ruby ![]() ![]() ![]()
Examples The problem we want to solve is as follows:
given a number of fields (with a name and a type)
how can we generate a Java class with getters and setters for those fields?
Here is a solution: module demo::common::StringTemplate import String; import IO; import Set; import List; // Capitalize the first character of a string public str capitalize(str s) {At ![]() capitalize is defined to capitalize the first character of a string.
The heavy lifting is done at ![]() genClass is defined that takes as arguments:
genClass returns a string that contains several string interpolations delimited by < and > .
Let's discuss some of them:
rascal>import demo::common::StringTemplate; ok rascal>import IO; ok rascal>fields = ( >>>>>>> "name" : "String", >>>>>>> "age" : "Integer", >>>>>>> "address" : "String" >>>>>>> ); map[str, str]: ("name":"String","address":"String","age":"Integer") rascal>println(genClass("Person", fields)); public class Person { private String address; public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } private Integer age; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } ok
Benefits
Pitfalls
![]() |