From 6b0a58afd7fb58f6709d42440e07c7ccec1dc3d7 Mon Sep 17 00:00:00 2001 From: Alysson Ribeiro <15274059+sonalys@users.noreply.github.com> Date: Fri, 15 Nov 2024 19:21:07 +0100 Subject: [PATCH] Feature(engine): allow developer to set their own default functions --- ast/DataContext.go | 6 +++++- engine/GruleEngine.go | 19 +++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/ast/DataContext.go b/ast/DataContext.go index b809d1c..75a90b1 100755 --- a/ast/DataContext.go +++ b/ast/DataContext.go @@ -17,10 +17,14 @@ package ast //go:generate mockgen -destination=../mocks/ast/DataContext.go -package=mocksAst . IDataContext import ( - "github.com/hyperjumptech/grule-rule-engine/model" "reflect" + + "github.com/hyperjumptech/grule-rule-engine/model" ) +// DefaultFuncKey defines the key used for default functions. +const DefaultFuncKey = "DEFUNC" + // NewDataContext will create a new DataContext instance func NewDataContext() IDataContext { diff --git a/engine/GruleEngine.go b/engine/GruleEngine.go index 1c62f62..6f9f4eb 100755 --- a/engine/GruleEngine.go +++ b/engine/GruleEngine.go @@ -17,11 +17,12 @@ package engine import ( "context" "fmt" - "github.com/sirupsen/logrus" - "go.uber.org/zap" "sort" "time" + "github.com/sirupsen/logrus" + "go.uber.org/zap" + "github.com/hyperjumptech/grule-rule-engine/ast" "github.com/hyperjumptech/grule-rule-engine/logger" ) @@ -130,13 +131,15 @@ func (g *GruleEngine) ExecuteWithContext(ctx context.Context, dataCtx ast.IDataC // Prepare the timer, we need to measure the processing time in debug mode. startTime := time.Now() - // Prepare the build-in function and add to datacontext. - defunc := &ast.BuiltInFunctions{ - Knowledge: knowledge, - WorkingMemory: knowledge.WorkingMemory, - DataContext: dataCtx, + if dataCtx.Get(ast.DefaultFuncKey) == nil { + // Prepare the build-in function and add to datacontext. + defunc := &ast.BuiltInFunctions{ + Knowledge: knowledge, + WorkingMemory: knowledge.WorkingMemory, + DataContext: dataCtx, + } + dataCtx.Add(ast.DefaultFuncKey, defunc) } - dataCtx.Add("DEFUNC", defunc) // Working memory need to be resetted. all Expression will be set as not evaluated. log.Debugf("Resetting Working memory")