Drools Rules: How can I use a method on "when" section?

manoelhc picture manoelhc · Mar 23, 2010 · Viewed 16.8k times · Source

I need to execute a method on "when" section of a DSLR file and I´m not sure if it´s possible. Example:

rule "WNPRules_10"
  when
    $reminder:Reminder(source == "HMI")
    $user:User(isInAgeRange("30-100")==true)
    Reminder(clickPercentual >= 10)
    User(haveAtLeastOptIns("1,2,3,4") == true)
  then
    $reminder.setPriority(1);update($reminder);
end

(note: isInAgeRange() and haveAtLeastOptIns() are methods of User)

I tried with eval() and no errors appeared, but it didn´t execute. Like this:

rule "WNPRules_10"
 when
  $reminder:Reminder(source == "HMI")
  $user:User(eval($user.isInAgeRange("30-100")==true))
  Reminder(clickPercentual >= 10)
  User(eval($user.haveAtLeastOptIns("1,2,3,4") == true))
 then
  $reminder.setPriority(1);update($reminder);
end

How can I resolve this problem?

Answer

Michael Neale picture Michael Neale · Mar 25, 2010

Your second attempt looks fairly confused - also - do you have so User patterns - do you want them to refer to the same instance of user? or can they be separate instances (or must they be separate?) - that will change things a bit in some cases depending on your intent.

In terms of the simplest rewrite I can think of:

  rule "WNPRules_10"
  when
    $reminder:Reminder(source == "HMI")
    $user:User()
    eval($user.isInAgeRange("30-100") && $user.haveAtLeastOptIns("1,2,3,4"))
    Reminder(clickPercentual >= 10)
  then
    $reminder.setPriority(1);update($reminder);
  end

Note the use of the eval() top level element - it also uses only one user pattern - and then applies the constraints to it. (In a future version inline evals will work without having to write eval !).