Search code examples
rubydelayed-job

Delayed Job seeking method


I have a module in a module in Ruby, something akin to:

Module Foo
  Module Bar
    def do_thing_as_delayed_job(my_id, my_option_array)
      Delayed::Job.enqueue Foo::Bar.do_thing(my_id, my_option_array)
    end
    def do_thing(my_id, my_option_array)
      Rails.logger.info("Yay, I got here!")
    end
  end
end

I try to fire of the delayed job starter. However, when I run do_thing_as_delayed_job, I get this:

NoMethodError: undefined method `do_thing' for Foo::Bar:Module

I don't know why it's searching in 'Module', how to make it just run the method I want. I'm still fairly new at Ruby. Thanks!


Solution

  • Foo::Bar.do_thing calls do_thing on the module itself. You've defined this method as def do_thing that makes it an instance method. It means that to call do_thing you need to have an instance of that class that has this module mixed in (1) or you need to change this method to a module method (2).

    Code for (1)

    class A
      include Foo::Bar
    end
    
    module Foo
      module Bar
        def do_thing_as_delayed_job(my_id, my_option_array)
          Delayed::Job.enqueue A.new.do_thing(my_id, my_option_array)
        end
        def do_thing(my_id, my_option_array)
          Rails.logger.info("Yay, I got here!")
        end
      end
    end
    

    Code for (2):

    
    module Foo
      module Bar
        def do_thing_as_delayed_job(my_id, my_option_array)
          Delayed::Job.enqueue A.new.do_thing(my_id, my_option_array)
        end
        def self.do_thing(my_id, my_option_array)
          Rails.logger.info("Yay, I got here!")
        end
      end
    end
    

    Note that in both cases module is lowecase.