2. What’s a “rule engine”?
system for executing IF-THEN statements
in ruleby these are called “production rules”
3. What’s wrong with IF-THEN
Complex code
Interdependencies
State transitions
Spaghetti code!
4. if firstname && lastname
if type == :group
if groupname
...
end
elsif type == :individual
...
end
end
Care to add a new ‘type’?
5. Ruleby: a better way
Rule-based programming
a rule engine that derives answers from a ‘knowledge
base’
the knowledge base contains the rules
give it facts to compare against the rules
6. 3 Parts of a rule engine
Facts :: data or objects, aka “working memory”
Rules :: the IF-THEN statements
Inference Engine :: an efficient mechanism for
executing the rules against the facts
7. The Ruleby inference engine
An implementation of the Rete algorithm that matches
patterns to objects
pronounced “ree-tee” or “ray-tee”
from Latin for “net” or Italian for “network”
Proposed by Dr. Charles Forgy in 1974 at CMU
was his PhD thesis in 1979 and a paper in 1984
8. Dirt Farmer’s guide to Rete
Builds a network of nodes from the rules
each node corresponds to a condition of a rule
Path from root to leaf defines a complete rule
As fact are asserted or modified they propagate along
the network and are evaluated at each node
When a fact or combination facts match all paterns for
a rule a leaf node is reached and the rule’s action is
fired
So what? It’s FAST, yo!
9. Using Ruleby, step 1
Build rules in a rule book using the DSL
rule conditions
action(s)
modifications to facts
modified facts are re-propragated thru network
13. Building rules
Rules are defined by the Ruleby DSL (“Ferrari” syntax)
Create multiple rules inside a single rule book method
allows you to organize, name and group rules
each rule is still independent
Can build rules dynamically (this is Ruby, ya know!)
14. Typical rule syntax
rule :identifier, [pattern] do |context|
# action(s)
end
15. Basic pattern syntax
[ClassType, :object_handle, cond_1, cond_n]
notes
- Class type is required
- :object_handle is optional (ref in block)
- 0 to n conditions
Let’s look at the hello.rb
example
16. Notes on conditions
Call methods on facts (objects) using method.x or m.x
Most examples show ==, there are others (<, >, etc.)
Can pass a block parameter that evals to T/F
use &condition{ ... } or &c{ ... } for short
condition is an alias for ‘lambda’
see cart_rulebook.rb example
17. Ruleby in a “real” Rails app
Put rule book in app/rules (don’t forget load_path)
Inherit from Ruleby::Rulebook
Define rules with conditions and actions
assert and/or modify facts (your Ruby objects)
18. Firing the Engine
Typically done in a controller
Create an engine
Get a rule book and initialize the rules
Assert facts
Call engine.match to fire it