Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Execute method in context of base class

I have about 20 different Active Jobs which I now realise are each going to need a before_perform method in which to set PaperTrail content outside the context of the controller.

I was planning on putting this before_perform method in a helper and then including the helper in each of the jobs but I am getting an error:

undefined method `before_perform' for MyApp:JobHelpers:Module

I am thinking that this is because the module in question is just that, a module and not an Active Job. How can I avoid repeating the same 4 line before_perform method in each of my Active Jobs?

Job_helper:

module MyApp
  module JobHelpers
    before_perform do |job|
      # stuff to do
    end
  end
end

The_job:

require 'my_app/job_helpers'

class TheJob < ActiveJob::Base
  include MyApp::JobHelpers

 # Do more stuff
end
like image 516
atw Avatar asked Apr 17 '26 18:04

atw


2 Answers

Rewrite your helper like this:

module MyApp
  module JobHelpers
    extend ActiveSupport::Concern

    included do

      # inside this you can call ActiveJob helpers
      before_perform do
        # stuff to do
      end
    end
  end
end
like image 79
dimakura Avatar answered Apr 20 '26 08:04

dimakura


I used an included callback to achieve my desired goal. I found a better description of the included callback than I could ever give in another answer here.

While other answers were similar, please find the solution that worked for me below:

module MyApp
  module JobHelpers
    def self.included(job_class)
      job_class.before_perform do |job|
        # work to be completed  
      end
    end
  end
end
like image 21
atw Avatar answered Apr 20 '26 07:04

atw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!