Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active April 18, 2024 00:50
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hopsoft/b17d8c1c90507917b898c431a41e3939 to your computer and use it in GitHub Desktop.
Save hopsoft/b17d8c1c90507917b898c431a41e3939 to your computer and use it in GitHub Desktop.
ActiveJob as Service Worker
# ActiveJob natively captures constructor arguments in an `@arguments` instance variable
# which is also exposed as an `arguments` property on each job instance.
#
# Calls to `perform_now` and `perform_later` both forward arguments to the constructor.
#
# For example, all of these invocation styles work.
#
# result = DoStuffJob.new("foobar").perform # sync
# result = DoStuffJob.new.perform("foobar") # sync
# result = DoStuffJob.perform_now("foobar") # sync
# DoStuffJob.perform_later("foobar") # async
#
# Note that all of the synchronous invocations return the result of the `perform` method.
#
# This allows ActiveJob to serve the role of "service object"
# with the added benefit of supporting asynchronous/backgrounded invocations.
#
# Also, we can override the consuctor to take more control if needed.
#
class DoStuffJob < ApplicationJob
def perform(message = nil)
message ||= arguments.first
# do stuff...
"This is the result: #{message}"
end
end
# You can also rename the `perform` method to match business semantics if desired.
#
class DoStuffJob < ApplicationJob
class << self
alias_method :do_the_thing_now, :perform_now
alias_method :do_the_thing_later, :perform_later
end
def perform(message = nil)
message ||= arguments.first
# do stuff...
"This is the result: #{message}"
end
alias_method :do_the_thing, :perform
end
# Override the constructor if you need more control over initialization
#
# Examples:
#
# DoStuffJob.new("foobar").perform
# DoStuffJob.new("foobar").perform("override")
# DoStuffJob.new.perform "foobar"
# DoStuffJob.perform_now "foobar"
#
class DoStuffJob < ApplicationJob
def initialize(message = nil)
super
@message = message
# custom initialization code...
end
def perform(message = nil)
message ||= @message
raise ArgumentError, "message is required" unless message
# do stuff...
"This is the result: #{message}"
end
end
# Use keyword arguments to enhance the job's interface
#
# Examples:
#
# DoStuffJob.new(message: "foobar").perform
# DoStuffJob.new(message: "foobar").perform(message: "override")
# DoStuffJob.new.perform message: "foobar"
# DoStuffJob.perform_now message: "foobar"
#
class DoStuffJob < ApplicationJob
def initialize(message: nil)
super
@message = message
# custom initialization code...
end
def perform(message: nil)
message ||= @message
raise ArgumentError, "message is required" unless message
# do stuff...
"This is the result: #{message}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment