From 142a342e530c45dea210f7d819f596fd2bbc33c1 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Fri, 14 Nov 2025 16:21:11 -0500 Subject: [PATCH] Make sure ActiveJob preserves the current account context This is a pretty common pattern, something like this is in both ActiveRecord::Tenanted and ActsAsTenanted. --- config/initializers/active_job.rb | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 config/initializers/active_job.rb diff --git a/config/initializers/active_job.rb b/config/initializers/active_job.rb new file mode 100644 index 000000000..340585f3b --- /dev/null +++ b/config/initializers/active_job.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +# inspired from code in ActiveRecord::Tenanted +module FizzyActiveJobExtensions + extend ActiveSupport::Concern + + prepended do + attr_reader :account + end + + def initialize(...) + super + @account = Current.account + end + + def serialize + super.merge({ "account" => @account&.to_gid }) + end + + def deserialize(job_data) + super + if _account = job_data.fetch("account", nil) + @account = GlobalID::Locator.locate(_account) + end + end + + def perform_now + if account.present? + Current.with_account(account) { super } + else + super + end + end +end + +ActiveSupport.on_load(:active_job) do + prepend FizzyActiveJobExtensions +end