在 IRB 中重新加载 ruby​​gem

发布于 2024-09-13 22:46:59 字数 148 浏览 5 评论 0 原文

有没有办法“重新加载”或“刷新”内存中的 ruby​​gem?当我在 irb 中玩时,偶尔我喜欢修改我的 gem 文件,如果我需要相同的 gem,它不会更新到内存中并给出输出“false”。目前我必须退出IRB,返回IRB,然后再次需要gem,必须有更好的方法......它是什么?

Is there a way to "reload" or "refresh" a rubygem in memory? As i'm playing in irb, occasionally I like to modify my gem files, and if i require the same gem, it does not update into memory and gives the output "false". Currently I have to exit IRB, get back into IRB and then require the gem again, there has to be a better way...what is it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若水般的淡然安静女子 2024-09-20 22:46:59

正如其他人所建议的,您可以使用 Kernel#load。但是,不要浪费时间查找和加载每个 gem 文件,因为所需的所有文件都存储在 $" 中。有了这些知识,这里有一个重新加载 irb 命令:

 def reload(require_regex)
  $".grep(/^#{require_regex}/).each {|e| load(e) }
 end

例如,如果您在 irb 中使用 hirb gem ,你只需重新加载:

>> reload 'hirb'

如果由于某种原因加载不起作用(它对文件扩展名比 require 更挑剔),你可以通过首先删除 $" 中的条目来重新请求任何文件。有了这个建议,上面的命令将是:

 def reload(require_regex)
   $".grep(/^#{require_regex}/).each {|e| $".delete(e) && require(e) }
 end

选择适合你的。就我个人而言,我使用后者。

As others have suggested, you can use Kernel#load. However, don't waste your time finding and loading each gem file as all files that have been required are stored in $". Armed with this knowledge, here's a reload irb command:

 def reload(require_regex)
  $".grep(/^#{require_regex}/).each {|e| load(e) }
 end

For example, if you were using the hirb gem in irb, you would simply reload with:

>> reload 'hirb'

If for whatever reason load doesn't work (it is pickier about file extensions than require is), you can re-require any file by first deleting its entry in $". With this advice the above command would be:

 def reload(require_regex)
   $".grep(/^#{require_regex}/).each {|e| $".delete(e) && require(e) }
 end

Pick whichever works for you. Personally, I use the latter.

吃颗糖壮壮胆 2024-09-20 22:46:59

加载一个“filename.rb” ...

为每个更改一次

load 'filename.rb'

one at a time for each that was changed...

長街聽風 2024-09-20 22:46:59

一种方法是使用Kernel#load。您可以像 Kernel#require 一样使用它,只不过您必须显式包含文件扩展名。但是,它也有其缺点(即使像 class Foo 这样简单的东西也会失败,因为不可能更改类的超类),所以我也想知道更好的方法来做到这一点。

在 Rails 中,您可以通过脚本/控制台上的 reload! 来实现此目的,但我不知道他们使用什么样的魔法。

这个要点看起来很有希望,但我还没有测试过。

One way is to use Kernel#load. You can use it pretty much like Kernel#require, except that you have to explicitly include the file extension. However, it has its drawbacks (even something as simple as class Foo < Struct.new(:foo); end fails, as it is not possible to change the superclass of an class), so I would also like to know a better way to do this.

In rails you can achieve this with reload! on script/console, but I don't know what kind of magic they use.

This gist looks promising but I haven't tested it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文