Skip to content

Instantly share code, notes, and snippets.

@michelson
Created April 23, 2024 01:50
Show Gist options
  • Save michelson/96128525b8a7d24aefa5e8b489190b82 to your computer and use it in GitHub Desktop.
Save michelson/96128525b8a7d24aefa5e8b489190b82 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
included do
# Extend both the class and instance to use async methods
extend AsyncMethods
singleton_class.extend AsyncMethods
end
module AsyncMethods
def method_missing(method_name, *args, queue: :default, &)
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)
queue_name = queue
AsyncMethodJob.perform_later(target: self, method_name: real_method, args: args, queue_name: queue_name)
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
end
class User
include Asynchronously
def some_method
puts "SOME METHOD CALL"
end
end
User.find_by_async(id: 1)
@user.some_method(id: 1)
@silva96
Copy link

silva96 commented Apr 26, 2024

Is this MIT license?

@michelson
Copy link
Author

yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment