Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override require in Ruby?

Tags:

ruby

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

Everything I tried gave me a stack overflow error.

What is the right way to do it?

like image 248
guai Avatar asked Dec 21 '22 07:12

guai


1 Answers

Generally, if you want to patch some built-in method, you should first make an alias for the original method. Most of the time you'll call the old one somewhere in your overriding method. Otherwise you'll lost the functionality of the original method and it's likely to break the application logic.

  1. Use ri require or read the documentation to find out where the require method is defined. You'll find it's in Kernel module. Besides, you'll find its method signature so you know what the parameter list looks like.
  2. Monkey patch module Kernel. DON'T break the functionality unless you 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'
like image 140
Arie Xiao Avatar answered Jan 01 '23 11:01

Arie Xiao