Skip to content

Sharing data within a workflow

Andrei Horak edited this page Mar 23, 2019 · 1 revision

Sometimes a workflow needs to share data to its tasks; or a task needs to know about the outcome of another task that preceeds it. For this, contexts can be used. Contexts are basically hashes that are passed through every task in a workflow. They can hold anything that is serializable. Every task can access the context that has been constructed so far¹ and can alter its contents². A context is persisted only if a task has been successfully processed.

¹ every job gets the latest available context upon processing, meaning that one should not rely on specific context items to be available when processing multiple tasks situated on the same dependency level, at the same time (e.g.: B -> A <- C; B and C can be processed simultaneously; if B adds item X on the context, C may or may not see item X) ² items can be added and updated on the context, but not removed

class CreateAccount < Pallets::Workflow
  task CreateRecord
  task SendConfirmation => CreateRecord
end

class CreateRecord < Pallets::Task
  def run
    account = Account.create!(user_id: context['user_id'], email: context['email'])
    # Tasks can contribute to the context
    context['account_id'] = account.id
  end
end

class CreateRecord < Pallets::Task
  def run
    # All context items contributed so far are available
    ConfirmationMailer.send(email: context['email'], account_id: context['account_id'])
  end
end

# Pass in a few details about the account
CreateAccount.new(user_id: 1234, email: '[email protected]')
Clone this wiki locally