Created
January 23, 2015 19:40
-
-
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
This file contains 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 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