share a variable between rules, use as condition in LHS

1,078 views
Skip to first unread message

Zorro

unread,
Nov 6, 2014, 1:57:06 PM11/6/14
to drools...@googlegroups.com
Hi guys,

I am trying to use a way to share a variable at runtime between the rules but without success.
I tried to use a global, but I understand that this is for read-only and I tried to use a fact, but that is always null.
I need to access this "something" in LHS to based my flow on it.

Let me explain what I tried.

The global version

Java code:

a. Loading the rules
   Navigator navigator = new Navigator();
   workingMemory.setGlobal("navigator", navigator);

b. Navigator.java

private String compass;

public String getCompass(){
    return this.compass;
}


public void setCompass(String compass){
    this.compass = compass;
}
....

Drools rules
.......
global Navigator navigator;


rule "Rule1"

when 
       condition 1
then
      navigator.setCompass("west");

end


rule "Rule2"
when 
       eval(navigator.getCompass()=="west")
then
      System.out.println("Go west");

end

Looks like Rule2 never gets executed although "Rule1" is called.

Now the fact version:

Java code:

Loading the rules
   Navigator navigator = new Navigator();
   workingMemory.insert(navigator);


Drools rules


rule "Rule1"

when 
       $navigator: Navigator()
then
      $navigator.setCompass("west");

end


rule "Rule2"
when 
       $navigator: Navigator(compass =="west")
then
      System.out.println("Go west");

end

How can I share at the runtime a variable in LHS between rules?

Thanks,
Z


Mark Proctor

unread,
Nov 6, 2014, 4:43:56 PM11/6/14
to drools...@googlegroups.com
Don’t set it as a global, insert it.

The engine will not react to globals.

If you really can’t insert it, for what reason I don’t know, you can do
Navigator() from navigator

Mark
--
You received this message because you are subscribed to the Google Groups "Drools Usage" group.
To unsubscribe from this group and stop receiving emails from it, send an email to drools-usage...@googlegroups.com.
To post to this group, send email to drools...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/drools-usage/63030181-905e-437c-b9a1-a669bce97930%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Davide Sottara

unread,
Nov 6, 2014, 5:15:54 PM11/6/14
to drools...@googlegroups.com
Your second version, using facts, seems the right way to do it. However, you can't just call "$navigator.setCompass(..)".. the engine will not be aware of the change and reevaluate the other rules.
You have to do something like modify ( $navigator ) { setCompass(...) }
Beware, though, of rules looping. See the manual for the details on "modify" and/or this blog post for details on how to deal with recursions
http://ilesteban.wordpress.com/2012/11/16/about-drools-and-infinite-execution-loops/
Best
Davide 

Reply all
Reply to author
Forward
0 new messages