manfred-kaiser/business-rule-engine

Doubt: Is there a way to declare rules in JSON?

ccrvlh opened this issue · 3 comments

I was wondering if it would be possible to replace the rule definition from a string to JSON to a more seamless interaction with frontend code. Ideas?
Thanks for the lib, it's pretty awesome!

If you want to use the library in a web application I think it's not a good idea to add json pasing to the library.

The reason is, that each web application works in a different way. You should implement your own endpoint to your application, which is able to parse the json and create the rules.

I have added a new method add_rule to the RuleParser. So you don't need to parse the json and create the string representation. You should update to version >0.2.0, if you want to use the new method.

Example - add_rule-method:

# import the RuleParser
from business_rule_engine import RuleParser

# define custom functions
def order_more(items_to_order):
    print("you ordered {} new items".format(items_to_order))
    return items_to_order

# create the ruleparser and register custom functions
parser = RuleParser()
parser.register_function(order_more)

# register the rules, this can be done in a for-loop.
# the first param must be a unique rule name
# second param is the condition
# third param is the action, which will be executed if the condition matches
parser.add_rule(
    rulename='testrule', 
    condition='products_in_stock < 20', 
    action='order_more(50)'
)

# params for the rules
params = {
    'products_in_stock': 10
}
# execute all rules
parser.execute(params)

@lowercase00 is the described solution ok for you? If not, how would you like to add json parsing to this library?

@manfred-kaiser thanks a lot for the answer, and sorry for the delay. Dynamic rules seems great, I'l just trying to think how to implement in my current project, where rules are defined in the frontend, hence my need to define as JSON.

Reading your answer (haven't implemented it yet), it seems to work for simple cases, since it would be just a string to be passed to the condition & action. I still wonder how to implement more complex rules, but I would have to advance in my current project to experience possible restrictions and come up with other ideas.

Anyways, again, thanks a lot for your answer, and congrats on the project, truly awesome, hope to use it a lot!
Also I'm happy to contribute if you think there's space.

Cheers!