运行/启动 ruby 时自动需要一个类
我正在一些 Ruby 类中做一些猴子修补,我希望每当我运行 Ruby 时自动包含这些修补程序。
例如:
我将方法trim添加到String中。我希望能够做到这一点:
ruby -e 'puts " aaaa ".trim'
我不想这样做:
ruby -e 'require "monkey.rb";放置“ aaaa”.trim'
每当我启动 ruby 时是否都包含我的猴子补丁? irb 怎么样?
谢谢!
I am doing some monkey patching in some of Ruby classes and I would like that to be included AUTOMATICALLY whenever I run ruby.
For example:
I added the method trim to String. I want to be able to do this:
ruby -e 'puts " aaaa ".trim'
I don't want to do this:
ruby -e 'require "monkey.rb"; puts " aaaa ".trim'
Is there anyway to include my monkey patches evertime I start ruby? How about irb?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ruby
和irb
都采用-r
选项,让您在运行这些可执行文件时指定要加载的库。如果您想自动加载monkey.rb
库,您可以通过调用$ ruby -r Monkey
启动ruby
(假设Monkey.rb
位于您的$RUBYLIB
路径中。如果您不想每次都这样做,您可以在 shell 配置文件中设置一个别名(例如在 Bash 中)。 ),您可以添加:ruby
andirb
both take a-r
option that lets you specify a library to load when running those executables. If you want to automatically load yourmonkey.rb
library, you can startruby
with the invocation$ ruby -r monkey
(assumingmonkey.rb
is in your$RUBYLIB
path. If you don't want to do that each time, you can set up an alias in your shell config file. For example (in Bash), you could add:irb 可能是您可以最简单地完成此操作的地方。使用 irb 时,您可以使用初始化文件来存储您想要在每次启动时运行的任何内容。在你的主目录(“cd ~”)中,创建一个名为“.irbrc”的文件,然后放入“require 'monkey.rb'”语句,这样就可以了。从那时起,当您启动 irb 时,它将首先运行该脚本中的任何内容。
irb is probably the place where you can do this most simply. When using irb, you can use an initialization file to store anything you want run on every startup. In your home directory ("cd ~"), create a file called ".irbrc", and drop in your "require 'monkey.rb'" statement, that should do it. From then on when you start up irb, it will run anything in that script first.