如何在 Ruby 中覆盖 require? [英] How to override require in Ruby?
问题描述
我需要从一个 Ruby 文件中覆盖 require
,这是我的 start.rb 所必需的,它是应用程序入口点.rubygems
在此之前加载,在 start.rb 中.
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.
正确的做法是什么?
推荐答案
一般来说,如果你想修补一些内置方法,你应该先为原始方法制作一个别名.大多数情况下,您会在覆盖方法的某处调用旧的.否则,您将失去原始方法的功能,并且很可能会破坏应用程序逻辑.
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.
- 使用
ri require
或阅读文档以找出require
方法的定义位置.您会在Kernel
模块中找到它.此外,您会找到它的方法签名,以便您了解参数列表的样子. - Monkey 补丁模块
Kernel
.不要破坏功能,除非您知道自己在做什么.
- Use
ri require
or read the documentation to find out where therequire
method is defined. You'll find it's inKernel
module. Besides, you'll find its method signature so you know what the parameter list looks like. - 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'
这篇关于如何在 Ruby 中覆盖 require?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!