mirror of
https://github.com/danog/liquid.git
synced 2024-11-26 23:04:38 +01:00
Support registering variadic functions as filters
This commit is contained in:
parent
fd7b1f0875
commit
82a1a6ebb1
@ -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()}
|
||||
}
|
||||
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)
|
||||
|
@ -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")
|
||||
|
Loading…
Reference in New Issue
Block a user