lib/torm/rules_engine.rb in torm-0.1.0 vs lib/torm/rules_engine.rb in torm-0.2.0

- old
+ new

@@ -21,10 +21,16 @@ @dirty end # Add a new rule. # Will mark the engine as dirty when a rules was added. + # + # @param [String] name + # @param [true, false, String, Numeric, Range, Hash] value Either a simple type, or a Range, or a Hash with a :minimum or :maximum key to represent a Range extreme. + # @param [Symbol] policy The source of the rule and thus how heavy it weighs. + # @param [Hash] conditions Conditions that must be met before a rule evaluates to return this value. + # # @return [Torm::RulesEngine] (self) Returns the engine that rules were added to. def add_rule(name, value, policy, conditions={}) raise "Illegal policy: #{policy.inspect}, must be one of: #{policies.inspect}" unless policies.include?(policy) rules_array = rules_for(name) value = { minimum: value.min, maximum: value.max } if Range === value @@ -39,19 +45,44 @@ self end # Simple helper class to add the block DSL to add_rules class RuleVariationHelper - def initialize(engine, name) + def initialize(engine, name, **conditions) @engine = engine @name = name + @conditions = conditions end def variation(value, policy, **conditions) - @engine.add_rule(@name, value, policy, conditions) + @engine.add_rule(@name, value, policy, @conditions.merge(conditions)) + nil end + + # @yield [Torm::RulesEngine::RulesVariationHelper] + def conditions(**conditions) + engine = self.class.new(@engine, @name, @conditions.merge(conditions)) + yield engine + nil + end end + # Add multiple rules via the block syntax: + # + # @example + # + # engine = Torm::RulesEngine.new + # engine.add_rules 'Happy', true, :default do |rule| + # rule.variant false, :default, rain: true + # end + # + # @param [String] name + # @param [true, false, String, Numeric, Range, Hash] value Either a simple type, or a Range, or a Hash with a :minimum or :maximum key to represent a Range extreme. + # @param [Symbol] policy The source of the rule and thus how heavy it weighs. + # + # @yield [Torm::RulesEngine::RuleVariationHelper] + # + # @return [Torm::RulesEngine] Returns self def add_rules(name, value, policy) # Add the default rule add_rule(name, value, policy) rule_variation = RuleVariationHelper.new(self, name)