-
-
Save whatcould/51110ceae9682ccc9842eee7eb4bfb8c to your computer and use it in GitHub Desktop.
Asynchronously Concern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class User | |
| include Asynchronously | |
| def some_method | |
| puts "SOME METHOD CALL" | |
| end | |
| end | |
| User.find_by_async(id: 1) | |
| @user.some_method(id: 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment