Skip to content

Commit

Permalink
fixed to handle pointer method (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
sio4 authored and markbates committed Dec 4, 2018
1 parent 93e0928 commit 4faa628
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,11 @@ func (c *compiler) evalCallExpression(node *ast.CallExpression) (interface{}, er
mname = i.Value
}
rv = rc.MethodByName(mname)
if !rv.IsValid() && rc.Type().Kind() != reflect.Ptr {
ptr := reflect.New(reflect.TypeOf(c))
ptr.Elem().Set(rc)
rv = ptr.MethodByName(mname)
}
if !rv.IsValid() {
if rv.Kind() == reflect.Slice {
rv = rc.FieldByName(mname)
Expand Down
26 changes: 26 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func Test_Render_UnknownAttribute_on_Callee(t *testing.T) {

type Robot struct {
Avatar Avatar
name string
}

type Avatar string
Expand All @@ -40,6 +41,10 @@ func (a Avatar) URL() string {
return strings.ToUpper(string(a))
}

func (r *Robot) Name() string {
return r.name
}

func Test_Render_Function_on_sub_Struct(t *testing.T) {
r := require.New(t)
ctx := NewContext()
Expand All @@ -52,3 +57,24 @@ func Test_Render_Function_on_sub_Struct(t *testing.T) {
r.NoError(err)
r.Equal("BENDER.JPG", s)
}

func Test_Render_Struct_PointerMethod(t *testing.T) {
r := require.New(t)
ctx := NewContext()
robot := Robot{name: "robot"}

t.Run("ByValue", func(t *testing.T) {
ctx.Set("robot", robot)
input := `<%= robot.Name() %>`
s, err := Render(input, ctx)
r.NoError(err)
r.Equal("robot", s)
})
t.Run("ByPointer", func(t *testing.T) {
ctx.Set("robot", &robot)
input := `<%= robot.Name() %>`
s, err := Render(input, ctx)
r.NoError(err)
r.Equal("robot", s)
})
}

0 comments on commit 4faa628

Please sign in to comment.