Skip to content

Instantly share code, notes, and snippets.

@edgarjs
Created January 23, 2015 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edgarjs/0d24a8b36bbf7e7d11c3 to your computer and use it in GitHub Desktop.
Save edgarjs/0d24a8b36bbf7e7d11c3 to your computer and use it in GitHub Desktop.
Default values and custom type handling before queuing a job. Just include this module in your ActiveJob class
module DefaultJobOptions
extend ActiveSupport::Concern
included do
before_enqueue do |job|
job.scheduled_at ||= 10.seconds.from_now.to_f
job.arguments = job.arguments_with_safe_types
end
end
def arguments_with_safe_types
arguments.map { |arg| cast_argument_to_safe_type(arg) }
end
def cast_argument_to_safe_type(argument)
case argument
when BigDecimal
argument.to_f
when ActiveRecord::AssociationRelation
argument.to_a
when Array
argument.map { |arg| cast_argument_to_safe_type(arg) }
when Hash
argument.each_with_object({}) do |(key, value), hash|
hash[ActiveJob::Arguments.send(:serialize_hash_key, key)] = cast_argument_to_safe_type(value)
end
else
argument
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment