Module: CMDx::Utils::Condition

Extended by:
Condition
Included in:
Condition
Defined in:
lib/cmdx/utils/condition.rb

Overview

Provides conditional evaluation utilities for CMDx tasks and workflows.

This module handles conditional logic evaluation with support for ‘if` and `unless` conditions using various callable types including symbols, procs, and objects responding to `call`.

Instance Method Summary collapse

Instance Method Details

#evaluate(target, options) ⇒ Boolean

Evaluates conditional logic based on provided options.

Supports both ‘if` and `unless` conditions, with `unless` taking precedence when both are specified. Returns true if no conditions are provided.

Examples:

Basic if condition

Condition.evaluate(user, if: :active?)
# => true if user.active? returns true

Unless condition

Condition.evaluate(user, unless: :blocked?)
# => true if user.blocked? returns false

Combined conditions

Condition.evaluate(user, if: :verified?, unless: :suspended?)
# => true if user.verified? is true AND user.suspended? is false

With arguments and block

Condition.evaluate(user, if: ->(u) { u.has_permission?(:admin) }, :admin)
# => true if the proc returns true when called with user and :admin

Parameters:

  • target (Object)

    The target object to evaluate conditions against

  • options (Hash)

    Conditional options hash

Options Hash (options):

  • :if (Object)

    Condition that must be true for evaluation to succeed

  • :unless (Object)

    Condition that must be false for evaluation to succeed

Returns:

  • (Boolean)

    true if conditions are met, false otherwise

Raises:

  • (RuntimeError)

    When a callable cannot be evaluated



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/cmdx/utils/condition.rb', line 56

def evaluate(target, options, ...)
  case options
  in if: if_cond, unless: unless_cond
    EVAL.call(target, if_cond, ...) && !EVAL.call(target, unless_cond, ...)
  in if: if_cond
    EVAL.call(target, if_cond, ...)
  in unless: unless_cond
    !EVAL.call(target, unless_cond, ...)
  else
    true
  end
end