rein - Rule Engine IN ruby

What's rein?

rein is simple rule engine in Ruby. rein enables to control applications that are filtering mails or validating data, etc. with rules.


Write rules in rule file and start rule engine with calling RuleEngine#fire(). The method receives an object to apply the rules.

require 'rein'
engine = "rules.yaml" obj

Rule file

Rule file is a YAML file. Write rules for rules at top level. Each rule requires name, condition, action.

An example of rule file is the following:

    name:      MailingList
    condition: from = ""
    action:    move "MailBox"

    name:      DearFriends
    condition: (from = "") or (from = "")
    action:    move "DearFriends"


Rule has "condition" and "action". When an object is matched the condition, the action is processed for the object.


Format of condition is "LHS(left hand side), operator, RHS(right hand side)". Write "and/or" to join conditions, "not" before a condition to deny. When you use the boolean operators, enclose a condition with parentheses. An example of condition is the following:

name =°∆MyName°«
register_date > '2000/1/1°«
(title =~ /R*/) and (name =~ /O*/)
not (time < 20)

String without quotation marks like "name" or "register_date" is a message for object to evaluate. The above conditions is parsed as ruby code the following: == 'MyName'
object.register_date > '2000/1/1'
(object.title =~ /R*/) and ( =~ /O*/)
not (object.time < 20)


Operators "=, !=, >, <, >=, <=, =~" are ready by default. To define a new operator, specify "operator string, method name (to evaluate the operator), object" with Qualifier.set_operator().

For example, we define "start" operator to evaluate whether LHS object starts with RHS string. First, define StartOperatorSupport class and start() method to evaluate the operator.

class StartOperatorSupport
  def self.start( left, right )
    left =~ /\A#{right}/

Next, set the operator with method name and class (or an object) evaluate.

Qualifier.set_operator('start', :start, StartOperatorSupport)


When an object is matched the condition, the action is processed for the object. You can specify an action or actions.

In now implementation, action is parsed with instance_eval() as Ruby code.

Conflict Resolution Strategies

If some rules match an object, rule engine applies one of the rules. In now version, you can set priority for rules to resolve conflict.

You can set priority between 0 and 1 for each rules. When rules conflict, rule engine applies a rule with highest priority. If highest priorities are, the engine applies a rule defined fastest in rule file.