grule-rule-engine
grule-rule-engine copied to clipboard
How can I add custom functon?
Hi, masters I found this https://github.com/hyperjumptech/grule-rule-engine/discussions/178 talking about this feature May I ask if this feature can be supported currently? I try to write a demo
package main
import (
"fmt"
"github.com/hyperjumptech/grule-rule-engine/ast"
"github.com/hyperjumptech/grule-rule-engine/builder"
"github.com/hyperjumptech/grule-rule-engine/engine"
"github.com/hyperjumptech/grule-rule-engine/pkg"
"time"
)
type MyFact struct {
IntAttribute int64
StringAttribute string
BooleanAttribute bool
FloatAttribute float64
TimeAttribute time.Time
WhatToSay string
UserSourceIP []string
}
func println(s string) {
fmt.Println("test", s)
}
func main() {
var err error
fact := &MyFact{
IntAttribute: 123,
StringAttribute: "Some string value",
BooleanAttribute: true,
FloatAttribute: 1.234,
TimeAttribute: time.Now(),
}
dataCtx := ast.NewDataContext()
if err = dataCtx.Add("MF", fact); err != nil {
panic(err)
}
if err = dataCtx.Add("println", println); err != nil {
panic(err)
}
drls := `
rule CheckValues "Check the default values" salience 10 {
when
MF.IntAttribute == 123 && MF.StringAttribute == "Some string value"
then
println(MF.StringAttribute);
Retract("CheckValues");
}`
knowledgeLibrary := ast.NewKnowledgeLibrary()
ruleBuilder := builder.NewRuleBuilder(knowledgeLibrary)
bs := pkg.NewBytesResource([]byte(drls))
err = ruleBuilder.BuildRuleFromResources("test", "0.0.1", []pkg.Resource{bs})
if err != nil {
fmt.Println(err.Error())
panic(err)
}
knowledgeBase, _ := knowledgeLibrary.NewKnowledgeBaseInstance("test", "0.0.1")
eng := engine.NewGruleEngine()
err = eng.Execute(dataCtx, knowledgeBase)
fmt.Println(fact.WhatToSay)
}
but it raised an error like this:
ERRO[0000] error while executing expression println(MF.StringAttribute). got this node identified as "DEFUNC" have no function named println lib=grule-rule-engine package=ast
ERRO[0000] Failed execution rule : CheckValues. Got error this node identified as "DEFUNC" have no function named println lib=grule-rule-engine package=engine