Class: StepperMotor::Conditional

Inherits:
Object
  • Object
show all
Defined in:
lib/stepper_motor/conditional.rb

Overview

A wrapper for conditional logic that can be evaluated against an object. This class encapsulates different types of conditions (booleans, symbols, callables, arrays) and provides a unified interface for checking if a condition is satisfied by a given object. It handles negation and ensures proper context when evaluating conditions.

Instance Method Summary collapse

Constructor Details

#initialize(condition, negate: false) ⇒ Conditional

Returns a new instance of Conditional.



9
10
11
12
13
# File 'lib/stepper_motor/conditional.rb', line 9

def initialize(condition, negate: false)
  @condition = condition
  @negate = negate
  validate_condition
end

Instance Method Details

#satisfied_by?(object) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/stepper_motor/conditional.rb', line 15

def satisfied_by?(object)
  result = case @condition
  when Array
    @condition.all? { |c| Conditional.new(c).satisfied_by?(object) }
  when Symbol
    !!object.send(@condition)
  when Conditional
    @condition.satisfied_by?(object)
  else
    if @condition.respond_to?(:call)
      !!object.instance_exec(&@condition)
    else
      !!@condition
    end
  end

  @negate ? !result : result
end