Skip to content

Commit

Permalink
Added replace helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ngerakines committed Mar 9, 2018
1 parent c12293b commit 42afb5c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ func lastPart(splitter, input interface{}) interface{} {
return parts[len(parts)-1]
}

func replace(old, new, input interface{}) interface{} {
newString := realString(new)
if newString == "" {
return input
}
oldString := realString(old)
if oldString == "" {
return input
}
inputString := realString(input)
if inputString == "" {
return input
}

return strings.Replace(inputString, oldString, newString, -1)
}

func splitCammelJoin(splitter, input interface{}) interface{} {
inputString := realString(input)
if inputString == "" {
Expand Down
23 changes: 23 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,29 @@ func TestSplitHelper(t *testing.T) {
}
}

func TestReplaceHelper(t *testing.T) {

tests := map[string]string{
`{{ "protocol.buffers" | replace "." "/" }}`: "protocol/buffers",
`{{ "goodbye.world" | replace "goodbye" "hello" | replace "." " " }}`: "hello world",
}

for templateData, expected := range tests {
funcMap := template.FuncMap{
"replace": replace,
}

tpl := template.Must(template.New("test").Funcs(funcMap).Parse(templateData))
var output bytes.Buffer
if err := tpl.Execute(&output, nil); err != nil {
t.Fatalf("%v", err)
}
if output.String() != expected {
t.Fatalf("Expected '%s' but got '%s'", expected, output.String())
}
}
}

func TestSplitCammelJoin(t *testing.T) {
tests := map[string]string{
`{{ "nick.gerakines" | splitCammelJoin "." }}`: "NickGerakines",
Expand Down
1 change: 1 addition & 0 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func RunPlugin(request *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGenerato
"lastPart": lastPart,
"splitCammelJoin": splitCammelJoin,
"hasServices": hasServices,
"replace": replace,
}

resp := new(plugin_go.CodeGeneratorResponse)
Expand Down

0 comments on commit 42afb5c

Please sign in to comment.