Class: MakesSense::DecisionTable
- Inherits:
-
Object
- Object
- MakesSense::DecisionTable
- Defined in:
- lib/makes_sense/decision_table.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(name, conditions, result_table, args) ⇒ DecisionTable
constructor
A new instance of DecisionTable.
- #validate ⇒ Object
- #with_ruleset(ruleset) ⇒ Object
Constructor Details
#initialize(name, conditions, result_table, args) ⇒ DecisionTable
Returns a new instance of DecisionTable.
10 11 12 13 14 15 |
# File 'lib/makes_sense/decision_table.rb', line 10 def initialize(name, conditions, result_table, args) @name = name @conditions = conditions @result_table = result_table @args = args end |
Class Method Details
.define(name, &block) ⇒ Object
17 18 19 20 21 |
# File 'lib/makes_sense/decision_table.rb', line 17 def self.define(name, &block) dsl = DecisionTableDsl.new dsl.instance_eval(&block) new(name, dsl.conditions, dsl.result_table, dsl.args) end |
Instance Method Details
#validate ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/makes_sense/decision_table.rb', line 23 def validate condition_values = @conditions.map(&:values) possible_conditions = condition_values[0].product(*condition_values[1..]) = = .map(&:conditions) errors = [] possible_conditions.each do |possible_condition| unless .include?(possible_condition) errors << { type: :missing, message: "Missing result condition: #{possible_condition}", expected_conditions: possible_condition, expected: {}.tap do |condition_map| @conditions.each_with_index do |condition, index| condition_map[condition.name] = possible_condition[index] end end } end end visited = [] .each do |row| found_index = visited.find_index(row.conditions) if found_index errors << { type: :duplicate, message: "Duplicate result #{row.conditions} for rows #{found_index} and #{row.row_index}", row: row, duplicate_index: found_index } end visited << row.conditions end if !errors.empty? Failure.new(errors) else Success.new(self) end end |
#with_ruleset(ruleset) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/makes_sense/decision_table.rb', line 69 def with_ruleset(ruleset) ->(**kwargs) do = ruleset_results = @conditions.map do |condition| method_kwarg_names = ruleset.method(condition.name).parameters.map { |parameter| parameter[1] } args = method_kwarg_names.map { |kwarg_name| kwargs[kwarg_name] } ruleset.public_send(condition.name, *args) end result_row = @result_table.rows.find do |row| row.conditions == ruleset_results end if result_row.results.respond_to?(:call) method_kwarg_names = result_row.results.parameters.map { |parameter| parameter[1] } args = method_kwarg_names.map { |kwarg_name| kwargs[kwarg_name] } result_row.results.call(*args) else result_row.results end end end |