Search code examples
ruby-on-railsmonkeypatchingrails-activejob

MonkeyPatching ActiveJobs


I am having an issue monkey-patching part of ActiveJobs. I have the following code in config/initializers/extensions/arguements.rb

module ActiveJob
  module Arguments
    TYPE_WHITELIST = [ Date, DateTime, Time, NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum ]
  end
end

Basically, I am trying to add basic support for Date/Time objects for use in the ActiveJob created by ActionMailer#deliver_later

Upon loading the rails app I can see my whitelist is loaded, however when I call the deliver_later method on a mailer the original whitelist overrides my patch.

#List is correct when app loads
2.1.2 :002 > ActiveJob::Arguments::TYPE_WHITELIST
 => [Date, DateTime, Time, NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum] 

#List is overridden by default list in ActiveJobs after running #deliver_later
2.1.2 :005 > ActiveJob::Arguments::TYPE_WHITELIST
 => [NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum] 

How can I make my modified whitelist stick? I am pretty sure the error stems from the original ActiveJob::Arguments not loading until deliver_later is called, and therefore loads after my patch and overrides it, though I am not sure how to fix that.


Solution

  • Edit: do not use, see https://stackoverflow.com/a/50743819/3293310


    What about this ?

    module ActiveJob
      module Arguments 
        remove_const(:TYPE_WHITELIST)
        TYPE_WHITELIST = [ Date, DateTime, Time, NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum ]
      end
    end
    

    Then, as said in the comments you should extend this module :

    module ActionMailer 
      class DeliveryJob < ActiveJob::Base 
        extend ActiveJob::Arguments 
      end
    end
    

    A better way if you're using ruby 2+ would be tu use Refinements. Unfortunately, you can't change constants with refinements (read Matz' comment here)