-
-
Save whatcould/43a3a3343e2917d06695842aaf371018 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 | |
| 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 |
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(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