1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-30 10:29:01 +01:00

Merge pull request #27 from Proximaio/feature/variadic_filters

Support registering variadic functions as filters
This commit is contained in:
Oliver Steele 2017-07-26 10:07:04 -04:00 committed by GitHub
commit 2353433e66
2 changed files with 25 additions and 4 deletions

View File

@ -43,12 +43,21 @@ func convertCallResults(results []reflect.Value) (interface{}, error) {
// Convert args to match the input types of function fn.
func convertCallArguments(fn reflect.Value, args []interface{}) (results []reflect.Value, err error) {
rt := fn.Type()
if len(args) > rt.NumIn() {
if len(args) > rt.NumIn() && !rt.IsVariadic() {
return nil, &CallParityError{NumArgs: len(args), NumParams: rt.NumIn()}
}
results = make([]reflect.Value, rt.NumIn())
if rt.IsVariadic() {
results = make([]reflect.Value, len(args))
} else {
results = make([]reflect.Value, rt.NumIn())
}
for i, arg := range args {
typ := rt.In(i)
var typ reflect.Type
if rt.IsVariadic() && i >= rt.NumIn()-1 {
typ = rt.In(rt.NumIn() - 1).Elem()
} else {
typ = rt.In(i)
}
switch {
case isDefaultFunctionType(typ):
results[i] = makeConstantFunction(typ, arg)

View File

@ -3,6 +3,7 @@ package evaluator
import (
"fmt"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/require"
@ -16,7 +17,18 @@ func TestCall(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "5,10.", value)
// extra arguments
// extra arguments (variadic)
fnVaridic := func(a string, b ...string) string {
return a + "," + strings.Join(b, ",") + "."
}
value, err = Call(reflect.ValueOf(fnVaridic), []interface{}{5, 10})
require.NoError(t, err)
require.Equal(t, "5,10.", value)
value, err = Call(reflect.ValueOf(fnVaridic), []interface{}{5, 10, 15, 20})
require.NoError(t, err)
require.Equal(t, "5,10,15,20.", value)
// extra arguments (non variadic)
_, err = Call(reflect.ValueOf(fn), []interface{}{5, 10, 20})
require.Error(t, err)
require.Contains(t, err.Error(), "wrong number of arguments")