Skip to content

Instantly share code, notes, and snippets.

@whatcould
Forked from michelson/async_method_job.rb
Last active October 15, 2025 14:30
Show Gist options
  • Save whatcould/43a3a3343e2917d06695842aaf371018 to your computer and use it in GitHub Desktop.
Save whatcould/43a3a3343e2917d06695842aaf371018 to your computer and use it in GitHub Desktop.
Asynchronously Concern
class AsyncMethodJob < ApplicationJob
queue_as :default
def perform(target:, method_name:, args:, queue_name: :default)
self.class.queue_as(queue_name)
# `target` could be either an instance or a class
target = target.constantize if target.is_a?(String) # Convert class name to class object if needed
target.send(method_name, *args)
end
end
module Asynchronously
extend ActiveSupport::Concern
module AsyncMethods
def method_missing(method_name, *args, &)
if method_name.to_s.end_with?("_async")
real_method = method_name.to_s[0..-7] # Remove '_async' suffix
if respond_to?(real_method, true)
if args.last.is_a?(Hash) && args.last.has_key?(:queue)
queue_name = args.pop[:queue]
else
queue_name = 'default'
end
AsyncMethodJob.set(queue: queue_name).perform_later(target: self, method_name: real_method, args: args)
else
super
end
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.end_with?("_async") || super
end
end
# Extend both the class and instance to use async methods
class_methods do
include AsyncMethods
end
included do
include AsyncMethods
end
end
class User
include Asynchronously
def some_method(val)
puts "SOME METHOD CALL WITH PARAMETER #{val}"
end
end
User.find_by_async(id: 1)
@user.some_method_async(5, queue: 'urgent')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment