j-easy / easy-rules

The simple, stupid rules engine for Java
https://github.com/j-easy/easy-rules/wiki
MIT License
4.83k stars 1.04k forks source link

How to get Rule with `when(String)` and `then(Action)`? #421

Open http600 opened 5 months ago

http600 commented 5 months ago

In a programmatic way with a fluent API:

Rule weatherRule = new RuleBuilder()
        .name("weather rule")
        .description("if it rains then take an umbrella")
        .when(facts -> facts.get("rain").equals(true))
        .then(facts -> System.out.println("It rains, take an umbrella!"))
        .build();

Or using an Expression Language:

Rule weatherRule = new MVELRule()
        .name("weather rule")
        .description("if it rains then take an umbrella")
        .when("rain == true")
        .then("System.out.println(\"It rains, take an umbrella!\");");

How to get:

...
        .when("rain == true")
        .then(facts -> System.out.println("It rains, take an umbrella!"))
...

Currently, I have to take it in:


        MVELRule weatherMvelRule = new MVELRule()
                .name("weather rule")
                .description("if it rains then take an umbrella")
                .when("rain == true");
        Facts facts = new Facts();
        facts.put("rain", true);
        if (weatherMvelRule.evaluate(facts)) {
            System.out.println("It rains, take an umbrella!");
        }