@@ -51,6 +51,15 @@ slurp <- function(file) {
5151 ), collapse = " \n " )
5252}
5353
54+ # Perform a series of pattern replacements on str.
55+ # Example: renderTemplate("foo ${x} bar ${y} baz ${x}", list(x = 1, y = 2))
56+ # Produces: "foo 1 bar 2 baz 1"
57+ renderTemplate <- function (str , substitutions ) {
58+ Reduce(function (str , name ) {
59+ gsub(paste0(" \\ $\\ {" , name , " \\ }" ), substitutions [[name ]], str )
60+ }, names(substitutions ), str )
61+ }
62+
5463capName = function (name ){
5564 paste0(toupper(substring(name , 1 , 1 )), substring(name , 2 ))
5665}
@@ -59,7 +68,7 @@ addWidgetConstructor <- function(name, package, edit){
5968 tpl <- slurp(' templates/widget_r.txt' )
6069 if (! file.exists(file_ <- sprintf(" R/%s.R" , name ))){
6170 cat(
62- sprintf (tpl , name , name , package , name , name , name , name , name , name , package , name , capName(name ), name , name , name ),
71+ renderTemplate (tpl , list ( name = name , package = package , capName = capName(name )) ),
6372 file = file_
6473 )
6574 message(' Created boilerplate for widget constructor ' , file_ )
@@ -93,7 +102,7 @@ addWidgetYAML <- function(name, edit){
93102}
94103
95104addPackageJSON <- function (npmPkg ) {
96- tpl <- sprintf (slurp(' templates/widget_package.json.txt' ), npmPkg )
105+ tpl <- renderTemplate (slurp(' templates/widget_package.json.txt' ), list ( npmPkg = npmPkg ) )
97106 if (! file.exists(' package.json' )) {
98107 cat(tpl , file = ' package.json' )
99108 message(' Created package.json' )
@@ -103,7 +112,7 @@ addPackageJSON <- function(npmPkg) {
103112}
104113
105114addWebpackConfig <- function (name ) {
106- tpl <- sprintf (slurp(' templates/widget_webpack.config.js.txt' ), name , name )
115+ tpl <- renderTemplate (slurp(' templates/widget_webpack.config.js.txt' ), list ( name = name ) )
107116 if (! file.exists(' webpack.config.js' )) {
108117 cat(tpl , file = ' webpack.config.js' )
109118 message(' Created webpack.config.js' )
@@ -120,7 +129,7 @@ addWidgetJS <- function(name, edit){
120129 dir.create(' srcjs' )
121130 }
122131 if (! file.exists(file_ <- sprintf(' srcjs/%s.js' , name ))){
123- cat(sprintf (tpl , name ), file = file_ )
132+ cat(renderTemplate (tpl , list ( name = name ) ), file = file_ )
124133 message(' Created boilerplate for widget javascript bindings at ' ,
125134 sprintf(' srcjs/%s.js' , name )
126135 )
@@ -131,7 +140,7 @@ addWidgetJS <- function(name, edit){
131140}
132141
133142addExampleApp <- function (name ) {
134- tpl <- sprintf (slurp(' templates/widget_app.R.txt' ), name , name , capName(name ), name )
143+ tpl <- renderTemplate (slurp(' templates/widget_app.R.txt' ), list ( name = name , capName = capName (name )) )
135144 if (! file.exists(' app.R' )) {
136145 cat(tpl , file = ' app.R' )
137146 message(' Created example app.R' )
0 commit comments