我注意到在一些 gems 中,当你简单地 require 'some_gem'
时,方法就会出现(据我所知没有任何猴子修补)。我在 Sinatra、Rake、Rails 和许多其他帮助程序库等一些 gem 中看到过它。如何在自己的图书馆中实现这一目标?
例子:
require 'sinatra'
# Automatically recieve the 'get' method
get('/') { "I was monkeypatched or included automatically." }
如果是 monkeypatching,哪些类/模块对于 monkeypatching 是通用的(除了 String、Numeric、Array 等)。
最佳答案
Sinatra 本质上是将它们添加为全局方法。当你需要 sinatra 时,它 extends the Object class使用在 sinatra/base.rb 中定义的 Sinatra::Delegator
. get
和put
等方法定义在base 中,并通过delegator 添加。
关于ruby - 在 Ruby 中动态地将方法获取到纯文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582920/