Question

I have a situation like below:

Module Task
  def get(a)
      fetch(a)
  end

  def fetch(a)
      query(a)
  end

  def query(a)
      puts a
  end
end

and only get method is called from outside of module like

Task.get('name')

I want to monkey patch only method query to make some change in response of get method since it calls query intern.

Please suggest a way to do this.

Was it helpful?

Solution

In order to monkey patch in cases like these, we need to include a file in lib folder. In this case you need to make a file inside lib folder of the same name. In that first include the module TASK and then use MODULENAME.module_eval and add the methods in this. In this file u can override the methods in the actual module and add methods to it too. In order for this to work you will have to require the file u created in lib in config/initializers/app.rb

Incase the module you are over riding is present inside a folder (like in case of a ruby gem) you need to include the whole path. For ex.

Module_1.Module_2.module_eval

where module 2 is inside module 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top