4

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
guai
  • 780
  • 1
  • 12
  • 29
  • Why are you even trying to do this? Why do you need it? – Robert K Mar 27 '13 at 14:47
  • 1
    There is no right way to do this. You shouldn't. – Damien MATHIEU Mar 27 '13 at 14:48
  • 1
    Rubygems does it, why I shouldn't? – guai Mar 27 '13 at 14:49
  • There is a lot of code, which I do not want to manually edit. I just need to rewrite require pathes in some cases – guai Mar 27 '13 at 14:51
  • 2
    The right way to do it is to start by showing what you've written. It's a lot easier for us to correct a problem than it is to write an entire solution from scratch. – the Tin Man Mar 27 '13 at 14:57
  • @guai If you want to rewrite paths, you'll interfere with both RubyGems and Bundler. I suggest that you alter `$:` instead to change the search paths. http://stackoverflow.com/questions/8636328/what-does-do-to-rubys-require-path – Robert K Mar 27 '13 at 19:52
  • @DamienMATHIEU this would be a place where it might be useful :) https://github.com/soveran/cargo/issues/1#issuecomment-120707838 – bbozo Jan 06 '16 at 09:22

1 Answers1

11

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'
Arie Xiao
  • 13,909
  • 3
  • 31
  • 30