Class: Strategize::Rule

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

Overview

The Rule class represents a predicate function that can be run against a specific subject.

Define a new rule Rule.new :rule_name, -> { code to execute }

Evaluate a rule rule = Rule.new :rule_name, -> { true } rule.evaluate(nil) #=> true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, predicate) ⇒ Rule

Create a new rule

Parameters:

  • name (Symbol)

    a descriptive name for the rule

  • predicate (Proc)

    code block to be executed



18
19
20
21
22
23
24
25
# File 'lib/strategize/rules/rule.rb', line 18

def initialize(name, predicate)
  unless predicate.respond_to?(:call)
    raise InvalidPredicateError, 'Invalid predicate function passed'
  end

  @name = name
  @predicate = predicate
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/strategize/rules/rule.rb', line 12

def name
  @name
end

#predicateObject (readonly)

Returns the value of attribute predicate.



12
13
14
# File 'lib/strategize/rules/rule.rb', line 12

def predicate
  @predicate
end

Instance Method Details

#evaluate(subject) ⇒ Boolean

Execute the predicate against the subject

Parameters:

  • subject (Object)

Returns:

  • (Boolean)


31
32
33
# File 'lib/strategize/rules/rule.rb', line 31

def evaluate(subject)
  subject.instance_exec(&@predicate)
end