Allows invokable to be carried outside the context

This commit is contained in:
Leon Mika 2024-05-06 01:47:17 +00:00
parent f7db399037
commit 34a0c8e3ff
2 changed files with 39 additions and 0 deletions

View file

@ -216,7 +216,15 @@ type Invokable struct {
ec *evalCtx ec *evalCtx
} }
func (i Invokable) IsNil() bool {
return i.inv == nil
}
func (i Invokable) Invoke(ctx context.Context, args ...any) (any, error) { func (i Invokable) Invoke(ctx context.Context, args ...any) (any, error) {
if i.inv == nil {
return nil, nil
}
var err error var err error
invArgs := invocationArgs{ invArgs := invocationArgs{
eval: i.eval, eval: i.eval,

View file

@ -290,6 +290,37 @@ func TestCallArgs_CanBind(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "[[HELLO]]", res) assert.Equal(t, "[[HELLO]]", res)
}) })
t.Run("can carry invokable outside of context", func(t *testing.T) {
inst := ucl.New()
var inv ucl.Invokable
inst.SetBuiltin("wrap", func(ctx context.Context, args ucl.CallArgs) (any, error) {
if err := args.Bind(&inv); err != nil {
return nil, err
}
return nil, nil
})
ctx := context.Background()
assert.True(t, inv.IsNil())
before, err := inv.Invoke(ctx, "hello")
assert.NoError(t, err)
assert.Nil(t, before)
res, err := inst.Eval(ctx, `wrap { |x| toUpper $x }`)
assert.NoError(t, err)
assert.Nil(t, res)
assert.False(t, inv.IsNil())
after, err := inv.Invoke(ctx, "hello")
assert.NoError(t, err)
assert.Equal(t, "HELLO", after)
})
} }
func TestCallArgs_MissingCommandHandler(t *testing.T) { func TestCallArgs_MissingCommandHandler(t *testing.T) {