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 = {}) ⇒ Task

Returns A new task instance.

Examples:

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

Parameters:

  • context (Hash, Context) (defaults to: {})

    The initial context for the task

Options Hash (context):

  • :* (Object)

    Any key-value pairs to initialize the context

Raises:



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

def initialize(context = {})
  Deprecator.restrict(self)

  @attributes = {}
  @errors = Errors.new

  @id = Identifier.generate
  @context = Context.build(context)
  @result = Result.new(self)
  @chain = Chain.build(@result)
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



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



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



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



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



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



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


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

def attributes(...)
  register(:attribute, Attribute.build(...))
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



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

def deregister(type, object, ...)
  case type
  when :attribute then settings[:attributes].deregister(object, ...)
  when :callback then settings[:callbacks].deregister(object, ...)
  when :coercion then settings[:coercions].deregister(object, ...)
  when :middleware then settings[:middlewares].deregister(object, ...)
  when :validator then settings[:validators].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")
if result.success?
  puts "Task completed successfully"
end

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



250
251
252
253
254
# File 'lib/cmdx/task.rb', line 250

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")
# Will raise an exception if execution fails

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



269
270
271
272
273
# File 'lib/cmdx/task.rb', line 269

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


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

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



148
149
150
151
152
153
154
155
156
157
# File 'lib/cmdx/task.rb', line 148

def register(type, object, ...)
  case type
  when :attribute then settings[:attributes].register(object, ...)
  when :callback then settings[:callbacks].register(object, ...)
  when :coercion then settings[:coercions].register(object, ...)
  when :middleware then settings[:middlewares].register(object, ...)
  when :validator then settings[:validators].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



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

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

.requiredObject

Examples:

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


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

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

.settings(**options) ⇒ Hash

Returns The merged settings hash.

Examples:

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

Parameters:

  • options (Hash)

    Configuration options to merge with existing settings

Options Hash (**options):

  • :* (Object)

    Any configuration option key-value pairs

Returns:

  • (Hash)

    The merged settings hash



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/cmdx/task.rb', line 113

def settings(**options)
  @settings ||= begin
    hash =
      if superclass.respond_to?(:settings)
        parent = superclass.settings
        parent
          .except(:backtrace_cleaner, :exception_handler, :logger, :deprecate)
          .transform_values!(&:dup)
          .merge!(
            backtrace_cleaner: parent[:backtrace_cleaner] || CMDx.configuration.backtrace_cleaner,
            exception_handler: parent[:exception_handler] || CMDx.configuration.exception_handler,
            logger: parent[:logger] || CMDx.configuration.logger,
            deprecate: parent[:deprecate]
          )
      else
        CMDx.configuration.to_h
      end

    hash[:attributes] ||= AttributeRegistry.new
    hash[:tags] ||= []

    hash.merge!(options)
  end
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



286
287
288
289
# File 'lib/cmdx/task.rb', line 286

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

#loggerLogger

Returns The logger instance for this task.

Examples:

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

Returns:

  • (Logger)

    The logger instance for this task



313
314
315
316
317
318
319
320
# File 'lib/cmdx/task.rb', line 313

def logger
  @logger ||= begin
    logger = self.class.settings[:logger] || CMDx.configuration.logger
    logger.level = self.class.settings[:log_level] || logger.level
    logger.formatter = self.class.settings[:log_formatter] || logger.formatter
    logger
  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



337
338
339
340
341
342
343
344
345
346
# File 'lib/cmdx/task.rb', line 337

def to_h
  {
    index: result.index,
    chain_id: chain.id,
    type: self.class.include?(Workflow) ? "Workflow" : "Task",
    tags: self.class.settings[:tags],
    class: self.class.name,
    id:
  }
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



355
356
357
# File 'lib/cmdx/task.rb', line 355

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:



302
303
304
# File 'lib/cmdx/task.rb', line 302

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