Class: CMDx::Task

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/cmdx/task.rb

Overview

Represents a task that can be executed within the CMDx framework. Tasks define attributes, callbacks, and execution logic that can be chained together to form workflows.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context = nil) ⇒ Task

Returns A new task instance.

Examples:

task = MyTask.new
task = MyTask.new(name: "example", priority: :high)
task = MyTask.new(Context.build(name: "example"))

Parameters:

  • context (Hash, Context, nil) (defaults to: nil)

    The initial context for the task

Raises:

Rbs:

  • (untyped context) -> void



88
89
90
91
92
93
94
95
96
97
98
# File 'lib/cmdx/task.rb', line 88

def initialize(context = nil)
  Deprecator.restrict(self)

  @id = Identifier.generate
  @context = Context.build(context)
  @errors = Errors.new
  @result = Result.new(self)
  @chain = Chain.build(@result, dry_run: @context.delete(:dry_run))

  @attributes = {}
end

Instance Attribute Details

#attributesHash{Symbol => Object} (readonly)

Returns the hash of processed attribute values for this task.

Examples:

task.attributes # => { user_id: 42, user_name: "John" }

Returns:

  • (Hash{Symbol => Object})

    Hash of attribute names to their values

Rbs:

  • @attributes: Hash[Symbol, untyped]



19
20
21
# File 'lib/cmdx/task.rb', line 19

def attributes
  @attributes
end

#chainChain (readonly)

Returns the execution chain containing all task results.

Examples:

task.chain.results.size # => 3

Returns:

  • (Chain)

    The chain instance

Rbs:

  • @chain: Chain



71
72
73
# File 'lib/cmdx/task.rb', line 71

def chain
  @chain
end

#contextContext (readonly) Also known as: ctx

Returns the execution context for this task.

Examples:

task.context[:user_id] # => 42

Returns:

  • (Context)

    The context instance

Rbs:

  • @context: Context



49
50
51
# File 'lib/cmdx/task.rb', line 49

def context
  @context
end

#errorsErrors (readonly)

Returns the collection of validation and execution errors.

Examples:

task.errors.to_h # => { email: ["must be valid"] }

Returns:

  • (Errors)

    The errors collection

Rbs:

  • @errors: Errors



29
30
31
# File 'lib/cmdx/task.rb', line 29

def errors
  @errors
end

#idString (readonly)

Returns the unique identifier for this task instance.

Examples:

task.id # => "abc123xyz"

Returns:

  • (String)

    The task identifier

Rbs:

  • @id: String



39
40
41
# File 'lib/cmdx/task.rb', line 39

def id
  @id
end

#resultResult (readonly) Also known as: res

Returns the execution result for this task.

Examples:

task.result.status # => "success"

Returns:

  • (Result)

    The result instance

Rbs:

  • @result: Result



60
61
62
# File 'lib/cmdx/task.rb', line 60

def result
  @result
end

Class Method Details

.attributesObject Also known as: attribute

Examples:

attributes :name, :email
attributes :age, type: Integer, default: 18

Rbs:

  • (*untyped) -> void



184
185
186
# File 'lib/cmdx/task.rb', line 184

def attributes(...)
  register(:attribute, Attribute.build(...))
end

.attributes_schemaHash

Returns Hash of attribute names to their configurations.

Examples:

MyTask.attributes_schema #=> {
  user_id: { name: :user_id, method_name: :user_id, required: true, types: [:integer], options: {}, children: [] },
  email: { name: :email, method_name: :email, required: false, types: [:string], options: { default: nil }, children: [] },
  profile: { name: :profile, method_name: :profile, required: false, types: [:hash], options: {}, children: [
    { name: :bio, method_name: :bio, required: false, types: [:string], options: {}, children: [] },
    { name: :name, method_name: :name, required: true, types: [:string], options: {}, children: [] }
  ] }
}

Returns:

  • (Hash)

    Hash of attribute names to their configurations

Rbs:

  • () -> Hash[Symbol, Hash[Symbol, untyped]]



258
259
260
261
262
# File 'lib/cmdx/task.rb', line 258

def attributes_schema
  Utils::Wrap.array(settings.attributes).to_h do |attr|
    [attr.method_name, attr.to_h]
  end
end

.deregister(type, object) ⇒ Object

Examples:

deregister(:attribute, :name)
deregister(:callback, :before, MyCallback)

Parameters:

  • type (Symbol)

    The type of registry to deregister from

  • object (Object)

    The object to deregister

Raises:

  • (RuntimeError)

    If the registry type is unknown

Rbs:

  • (Symbol type, untyped object, *untyped) -> void



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/cmdx/task.rb', line 166

def deregister(type, object, ...)
  case type
  when :attribute
    settings.attributes.undefine_readers_on!(self, object)
    settings.attributes.deregister(object)
  when :callback then settings.callbacks.deregister(object, ...)
  when :middleware then settings.middlewares.deregister(object, ...)
  when :validator then settings.validators.deregister(object, ...)
  when :coercion then settings.coercions.deregister(object, ...)
  else raise "unknown registry type #{type.inspect}"
  end
end

.execute(*args, **kwargs) ⇒ Result

Returns The execution result.

Examples:

result = MyTask.execute(name: "example")

Parameters:

  • args (Array)

    Arguments to pass to the task constructor

  • kwargs (Hash)

    Keyword arguments to pass to the task constructor

Options Hash (**kwargs):

  • :* (Object)

    Any key-value pairs to pass to the task constructor

Returns:

  • (Result)

    The execution result

Rbs:

  • (*untyped args, dry_run: bool, **untyped kwargs) ?{ (Result) -> void } -> Result



292
293
294
295
296
# File 'lib/cmdx/task.rb', line 292

def execute(*args, **kwargs)
  task = new(*args, **kwargs)
  task.execute(raise: false)
  block_given? ? yield(task.result) : task.result
end

.execute!(*args, **kwargs) ⇒ Result

Returns The execution result.

Examples:

result = MyTask.execute!(name: "example")

Parameters:

  • args (Array)

    Arguments to pass to the task constructor

  • kwargs (Hash)

    Keyword arguments to pass to the task constructor

Options Hash (**kwargs):

  • :* (Object)

    Any key-value pairs to pass to the task constructor

Returns:

  • (Result)

    The execution result

Raises:

  • (ExecutionError)

    If the task execution fails

Rbs:

  • (*untyped args, dry_run: bool, **untyped kwargs) ?{ (Result) -> void } -> Result



310
311
312
313
314
# File 'lib/cmdx/task.rb', line 310

def execute!(*args, **kwargs)
  task = new(*args, **kwargs)
  task.execute(raise: true)
  block_given? ? yield(task.result) : task.result
end

.optionalObject

Examples:

optional :description, :notes
optional :priority, type: Symbol, default: :normal

Rbs:

  • (*untyped) -> void



194
195
196
# File 'lib/cmdx/task.rb', line 194

def optional(...)
  register(:attribute, Attribute.optional(...))
end

.register(type, object) ⇒ Object

Examples:

register(:attribute, MyAttribute.new)
register(:callback, :before, -> { puts "before" })

Parameters:

  • type (Symbol)

    The type of registry to register with

  • object (Object)

    The object to register

Raises:

  • (RuntimeError)

    If the registry type is unknown

Rbs:

  • (Symbol type, untyped object, *untyped) -> void



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/cmdx/task.rb', line 143

def register(type, object, ...)
  case type
  when :attribute
    settings.attributes.register(object)
    settings.attributes.define_readers_on!(self, Utils::Wrap.array(object))
  when :callback then settings.callbacks.register(object, ...)
  when :middleware then settings.middlewares.register(object, ...)
  when :validator then settings.validators.register(object, ...)
  when :coercion then settings.coercions.register(object, ...)
  else raise "unknown registry type #{type.inspect}"
  end
end

.remove_attributes(*names) ⇒ Object Also known as: remove_attribute

Examples:

remove_attributes :old_field, :deprecated_field

Parameters:

  • names (Array<Symbol>)

    Names of attributes to remove

Rbs:

  • (*Symbol names) -> void



213
214
215
# File 'lib/cmdx/task.rb', line 213

def remove_attributes(*names)
  deregister(:attribute, names)
end

.remove_returns(*names) ⇒ Object Also known as: remove_return

Removes declared returns from the task.

Examples:

remove_returns :old_return

Parameters:

  • names (Array<Symbol>)

    Names of returns to remove

Rbs:

  • (*Symbol names) -> void



240
241
242
# File 'lib/cmdx/task.rb', line 240

def remove_returns(*names)
  settings.returns -= names.map(&:to_sym)
end

.requiredObject

Examples:

required :name, :email
required :age, type: Integer, min: 0

Rbs:

  • (*untyped) -> void



203
204
205
# File 'lib/cmdx/task.rb', line 203

def required(...)
  register(:attribute, Attribute.required(...))
end

.returns(*names) ⇒ Object

Declares expected context returns that must be set after task execution. If any declared return is missing from the context after #work completes successfully, the task will fail with a validation error.

Examples:

returns :user, :token

Parameters:

  • names (Array<Symbol, String>)

    Names of expected return keys in the context

Rbs:

  • (*untyped names) -> void



228
229
230
# File 'lib/cmdx/task.rb', line 228

def returns(*names)
  settings.returns |= names.map(&:to_sym)
end

.settings(**overrides) ⇒ Settings

Returns (and lazily creates) the task-level Settings object. On first access, inherits from the superclass settings or the global Configuration. Optional overrides are applied once.

Examples:

class MyTask < Task
  settings deprecate: true, tags: [:experimental]
end

Parameters:

  • overrides (Hash)

    Configuration overrides applied on first access

Options Hash (**overrides):

  • :* (Object)

    Any configuration override key-value pairs

Returns:

  • (Settings)

    The settings instance for this task class

Rbs:

  • (**untyped overrides) -> Settings



126
127
128
129
130
131
# File 'lib/cmdx/task.rb', line 126

def settings(**overrides)
  @settings ||= begin
    parent = superclass.settings if superclass.respond_to?(:settings)
    Settings.new(parent:, **overrides)
  end
end

.typeString

Returns the cached task type string for this class.

Returns:

  • (String)

    “Workflow” or “Task”

Rbs:

  • () -> String



107
108
109
# File 'lib/cmdx/task.rb', line 107

def type
  @type ||= include?(Workflow) ? "Workflow" : "Task"
end

Instance Method Details

#execute(raise: false) ⇒ Result

Returns The execution result.

Examples:

result = task.execute
result = task.execute(raise: true)

Parameters:

  • raise (Boolean) (defaults to: false)

    Whether to raise exceptions on failure

Returns:

  • (Result)

    The execution result

Rbs:

  • (raise: bool) ?{ (Result) -> void } -> Result



327
328
329
330
# File 'lib/cmdx/task.rb', line 327

def execute(raise: false)
  Executor.execute(self, raise:)
  block_given? ? yield(result) : result
end

#loggerLogger

Returns a logger for this task. When a custom log_level or log_formatter is configured, the shared logger is duplicated so the original instance is never mutated.

Examples:

logger.info "Starting task execution"
logger.error "Task failed", error: exception

Returns:

  • (Logger)

    The logger instance for this task

Rbs:

  • () -> Logger



358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/cmdx/task.rb', line 358

def logger
  @logger ||= begin
    settings = self.class.settings
    log_instance = settings.logger || CMDx.configuration.logger

    if settings.log_level || settings.log_formatter
      log_instance = log_instance.dup
      log_instance.level = settings.log_level if settings.log_level
      log_instance.formatter = settings.log_formatter if settings.log_formatter
    end

    log_instance
  end
end

#to_hHash

Returns A hash representation of the task.

Examples:

task_hash = task.to_h
puts "Task type: #{task_hash[:type]}"
puts "Task tags: #{task_hash[:tags].join(', ')}"

Parameters:

  • return (Hash)

    a customizable set of options

Returns:

  • (Hash)

    A hash representation of the task

Rbs:

  • () -> Hash[Symbol, untyped]



388
389
390
391
392
393
394
395
396
397
398
# File 'lib/cmdx/task.rb', line 388

def to_h
  {
    index: result.index,
    chain_id: chain.id,
    type: self.class.type,
    class: self.class.name,
    id:,
    dry_run: dry_run?,
    tags: self.class.settings.tags
  }
end

#to_sString

Returns A string representation of the task.

Examples:

puts task.to_s
# Output: "Task[MyTask] tags: [:important] id: abc123"

Returns:

  • (String)

    A string representation of the task

Rbs:

  • () -> String



407
408
409
# File 'lib/cmdx/task.rb', line 407

def to_s
  Utils::Format.to_str(to_h)
end

#workObject

Examples:

class MyTask < Task
  def work
    # Custom work logic here
    puts "Performing work..."
  end
end

Raises:

Rbs:

  • () -> void



343
344
345
# File 'lib/cmdx/task.rb', line 343

def work
  raise UndefinedMethodError, "undefined method #{self.class.name}#work"
end