Ruby-on-rails Rails 控制台可以重新加载 lib 下的模块吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6361401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can Rails console reload modules under lib?
提问by Chip Castle
I have a module in my Rails project under lib. I run 'rails c' and do some experimenting in the console. I make a change to the module under lib, type 'reload!' from the console and it doesn't reload the file. I have to quit the console and restart, which is real pain.
我的 Rails 项目中有一个模块位于 lib 下。我运行“rails c”并在控制台中进行一些实验。我对 lib 下的模块进行了更改,键入“reload!” 从控制台,它不会重新加载文件。我必须退出控制台并重新启动,这真的很痛苦。
Is there a better way to reload that file?
有没有更好的方法来重新加载该文件?
回答by NullRef
Try this:
尝试这个:
load "#{Rails.root}/lib/yourfile.rb"
回答by Huiming Teo
In case anyone interested, here's my findings on how to auto-reload require files in Railswithout restarting server.
如果有人感兴趣,这是我关于如何在不重新启动服务器的情况下自动重新加载 Rails 中的 require 文件的发现。
The solution is now available as a Ruby gem require_reloader.
该解决方案现在可作为 Ruby gem require_reloader 使用。
回答by Wouter Vegter
this is the monkeypatch that could help you, paste this in rails console (or you could put this code in a monkeypatch file - although I don't recommend monkeypatching Object with an utility method):
这是可以帮助您的monkeypatch,将其粘贴到rails控制台中(或者您可以将此代码放入monkeypatch文件中-尽管我不建议使用实用方法对对象进行monkeypatching对象):
class Object
def self.reload_myself!
method = (self.instance_methods(false) + self.methods(false)).select{|method| method.to_s[0] =~ /[A-Za-z]/}.last
if method
if self.instance_methods(false).index method
method = self.instance_method(method)
elsif
method = self.method(method)
end
if (method.source_location)
source_location = method.source_location[0]
puts "reloading: #{source_location}"
load "#{source_location}"
else
puts "could not reload #{self.name}"
end
end
end
end
and you can call
你可以打电话
reload_myself!
on any object to reload its source code.
在任何对象上重新加载其源代码。
回答by Abdo
Add the following to config/initializers/reload.rb
将以下内容添加到 config/initializers/reload.rb
class Object
def reload_lib!
Dir["#{Rails.root}/lib/**/*.rb"].map { |f| [f, load(f) ] } #.all? { |a| a[1] }
# uncomment above if you don't want to see all the reloaded files
end
end
You can now reload all the files in libby typing reload_lib!in the console
您现在可以lib通过reload_lib!在控制台中键入来重新加载所有文件

