How to override a requirement in Ruby?

I need to override require from the Ruby file, which is required from my start.rb, which is the entry point of the application. rubygems loaded before in start.rb.

Everything I tried gave me an error.

What is the right way to do this?

+3
ruby
source share
1 answer

Generally, if you want to fix some inline method, you must first create an alias for the original method. Most of the time you will call the old one somewhere in your override method. Otherwise, you will lose the functionality of the original method and most likely break the application logic.

  • Use ri require or read the documentation to find out where the require method is defined. You will find it in the Kernel module. In addition, you will find your method signature to find out what the parameter list looks like.
  • Patch module Monkey Kernel . DO NOT disrupt functionality if you do not know what you are doing.
 module Kernel # make an alias of the original require alias_method :original_require, :require # rewrite require def require name puts name original_require name end end # test the new require require 'date' 
+7
source share

All Articles