Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I add custom functon? #459

Open
Caratpine opened this issue Aug 13, 2024 · 0 comments
Open

How can I add custom functon? #459

Caratpine opened this issue Aug 13, 2024 · 0 comments

Comments

@Caratpine
Copy link

Hi, masters
I found this #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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant