Class: DecisionTable::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/decision_table/rule.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(criteria, result) ⇒ Rule

Returns a new instance of Rule.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/decision_table/rule.rb', line 6

def initialize(criteria, result)
  if criteria.is_a?(Hash)
    @criteria = criteria
    @result = result
  else
    @criteria = {}
    keys = criteria
    values = result
    keys.pop if keys.size == values.size
    keys.each_with_index { |key, index| @criteria[key] = values[index] }
    @result = values.last
  end
end

Instance Attribute Details

#criteriaObject

Returns the value of attribute criteria.



4
5
6
# File 'lib/decision_table/rule.rb', line 4

def criteria
  @criteria
end

#resultObject

Returns the value of attribute result.



4
5
6
# File 'lib/decision_table/rule.rb', line 4

def result
  @result
end

Class Method Details

.parse(rule_string) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/decision_table/rule.rb', line 36

def self.parse(rule_string)
  criteria = {}
  rule_string.split(",").each do |crit|
    k, v = crit.split(":")
    criteria[k] = v
  end
  Rule.new(criteria, true)
end

Instance Method Details

#applies?(candidate) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
# File 'lib/decision_table/rule.rb', line 20

def applies?(candidate)
  criteria.all? do |k, v|
    v.blank? || matches?(candidate, k, v)
  end
end

#matches?(candidate, key, value) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
# File 'lib/decision_table/rule.rb', line 26

def matches?(candidate, key, value)
  if value.to_s == "true"
    candidate.send(key)
  elsif value.to_s == "false"
    !candidate.send(key)
  else
    candidate.send(key) == value
  end
end