jruizgit / rules

Durable Rules Engine
MIT License
1.16k stars 206 forks source link

how to return a value from a consequent and capture it in the caller. #274

Open komalbb opened 5 years ago

komalbb commented 5 years ago

I am exploring the rule engine to build a tool to analyse the state changes of an entity and report the states and any capture any failure during the state change.

I couldn't find a. way to capture the return value once the consequent executes. Can you help me here with an example. I have gone through the py docs, all the consequents are only having print statements. Can you please add a example to return a custom value?

from durable.lang import *

with ruleset('test'):

antecedent

@when_all(m.subject == 'World')
def say_hello(c):
    # consequent
    print ('Hello {0}'.format(c.m.subject))
    c.m.out = {'komal': 'komal'}
    return "world"

def validate_opst(order_info): val = post('test', order_info) print(type(val), val) print(order_info)

The val is sometimes 0 and sometimes a json with Sid.

jruizgit commented 5 years ago

Hi, thanks for asking the question. You can use the context object passed to the consequent to record the outcome. For example:

from durable.lang import *

with ruleset('test'):
    # antecedent
    @when_all(m.subject == 'World')
    def say_hello(c):
        # consequent
        print('test-> Hello {0}'.format(c.m.subject))
        c.s.result = 'say_hello'

print(post('test', { 'subject': 'World' }))
komalbb commented 5 years ago

@jruizgit Thanks for the your quick response. This is greatly helpful, I tried the same on state flow, but the context state is not returned. After looking into the library, it seems that there a complete callback to be provided to get the callback once state flow is complete. The declaration looks to be like this: complete_cbk(msg, state). In all the cases, there surely will be a callback I hope. Please let me know if not, so I can handle that accordingly.