如何在 IRB 中重新加载脚本? [英] How can I reload a script in IRB?
问题描述
我正在编写一个在 Rails 环境中使用的 Ruby 脚本,但我选择从 irb 运行它,因为重新加载 Rails 控制台可能会很痛苦.现在 irb 的等待时间要短得多,但是我很烦恼我必须重新启动 irb 并且每次进行更改时都需要脚本.有没有更简单的方法可以从 irb 重新加载脚本?
I am writing a Ruby script for use in the Rails environment, but I chose to run it from irb because reloading the Rails console can be a pain. Now the wait time is much shorter from irb, but I'm bothered that I have to restart irb and require the script everytime I make a change. Is there a simpler way of reloading a script from irb?
我在这个线程中找到了一种方法,但显然只适用于 gem 文件.我的 require 语句看起来像这样
I found a method in this thread, but that only applies to gem files apparently. My require statement looks like this
require "#{File.expand_path(__FILE__)}/../lib/query"
尝试了 load
而不是 require
,我仍然无法让它工作.我无法停止这些错误.
Having tried load
rather than require
, I still couldn't get it to work. I can't get a stop on these errors.
ruby-1.9.2-p0 > load "#{File.expand_path(__FILE__)}/../lib/query.rb"
LoadError: no such file to load -- /Users/newuser/Dropbox/Sites/rails/hacknyc/(irb)/../lib/query.rb
推荐答案
在 irb 中,File.expand_path(__FILE__)}
只会返回 "#{path you running irb from}/(irb)"
.这会创建一条实际上并不存在的路径.幸运的是,所有文件路径都相对于您运行 irb 的位置.这意味着您只需要:
In irb, File.expand_path(__FILE__)}
will just return "#{path you ran irb from}/(irb)"
. Which creates a path that doesn't actually exist. Luckily all file paths are relative to where you ran irb anyway. This means all you need is:
load "lib/query.rb"
如果您想在实际文件中使用 __FILE__
,那很好,但不要期望它在 irb 中生成有效路径.因为 irb 根本没有文件",所以它根本无法返回有效路径.
If you want to use the __FILE__
in an actual file, that's fine, but don't expect it to produce a valid path in irb. Because an irb there is no "file" at all, so it cannot return valid path at all.
此外,如果在通过 load 或 require 加载到 irb 的文件中使用 __FILE__
将正常工作.因为这就是它的用途.
Also, __FILE__
will work fine if used in a file loaded into irb via load or require. Cause that's kinda what it's for.
这篇关于如何在 IRB 中重新加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!