【发布时间】:2011-09-08 11:28:12
【问题描述】:
我在我的 Rails 控制台中使用 Pry gem,但是 pry 风格的 rails-console 似乎失去了重新加载!重新加载模型和东西的方法。
下面是我如何启动 pry 控制台
c:\rails\app> pry -r ./config/environment
谢谢
【问题讨论】:
标签: ruby-on-rails pry
我在我的 Rails 控制台中使用 Pry gem,但是 pry 风格的 rails-console 似乎失去了重新加载!重新加载模型和东西的方法。
下面是我如何启动 pry 控制台
c:\rails\app> pry -r ./config/environment
谢谢
【问题讨论】:
标签: ruby-on-rails pry
使用重载!像 rails 控制台命令一样,将此代码添加到您的 .pryrc
# load Rails Console helpers like reload
require 'rails/console/app'
extend Rails::ConsoleMethods
puts 'Rails Console Helpers loaded'
编辑== Gem pry-rails 已经完成了所有这些工作,而且要简单得多。
【讨论】:
对于最近提出这个问题的任何人:Rails 3.2 中的答案已经改变,因为他们改变了实现reload! 的方式在早期版本中,irb 命令作为方法添加到Object,现在它们被添加到IRB::ExtendCommandBundle 以避免污染全局命名空间。
我现在做的是 (1) 在 development.rb 中
silence_warnings do
begin
require 'pry'
IRB = Pry
module Pry::RailsCommands ;end
IRB::ExtendCommandBundle = Pry::RailsCommands
rescue LoadError
end
end
和 .pryrc 中的 (2)
if Kernel.const_defined?("Rails") then
require File.join(Rails.root,"config","environment")
require 'rails/console/app'
require 'rails/console/helpers'
Pry::RailsCommands.instance_methods.each do |name|
Pry::Commands.command name.to_s do
Class.new.extend(Pry::RailsCommands).send(name)
end
end
end
这是引入更改的 Rails 拉取请求的链接 - https://github.com/rails/rails/pull/3509
【讨论】:
您可以在 Pry wiki 上查看此页面:https://github.com/pry/pry/wiki/Setting-up-Rails-or-Heroku-to-use-Pry
还可以查看pry-rails 插件:https://github.com/rweng/pry-rails
该 wiki 上还有很多其他内容,这是一个很好的资源。
【讨论】:
reload!
您可以告诉 Pry 在您的 .pryrc 中加载 Rails 环境
rails = File.join Dir.getwd, 'config', 'environment.rb'
if File.exist?(rails) && ENV['SKIP_RAILS'].nil?
require rails
if Rails.version[0..0] == "2"
require 'console_app'
require 'console_with_helpers'
elsif Rails.version[0..0] == "3"
require 'rails/console/app'
require 'rails/console/helpers'
else
warn "[WARN] cannot load Rails console commands (Not on Rails2 or Rails3?)"
end
end
这将返回您的reload!。
【讨论】:
include Rails::ConsoleMethods
如果您在使用 Zeus 和 Pry 时遇到问题,请尝试添加到您的 .pryrc:
if Kernel.const_defined?(:Rails) && Rails.env
require File.join(Rails.root,"config","environment")
require 'rails/console/app'
require 'rails/console/helpers'
extend Rails::ConsoleMethods
end
取自here
【讨论】:
我最近写了一篇关于 pry 和 rails 的文章。你可以在这里找到它http://lucapette.com/pry/pry-everywhere/。顺便说一句,正如 dave 已经说过的,您想使用 pry with:
pry -r ./config/environment
我建议你试试我在文章中写的,效果很好。
【讨论】:
RAILS_ENV=production pry -r ./config/environment。
alias pryr="pry -r ./config/environment -r rails/console/app -r rails/console/helpers"
【讨论】:
你的意思是./config/environment?
无论如何,我认为这与实际启动 rails 控制台不同,这是 reload! 的来源。我在特定于 env 的配置文件中重新定义了 IRB = Pry,这确保了一个完整的控制台,并且一切都像一个魅力。
【讨论】:
@Rodrigo Dias 的answer 的更好版本。
如果您不想使用pry-rails gem,那么只需将以下内容添加到您的.pryrc-
if defined?(Rails) && Rails.env
if defined?(Rails::ConsoleMethods)
include Rails::ConsoleMethods
else
def reload!(print=true)
puts "Reloading..." if print
ActionDispatch::Reloader.cleanup!
ActionDispatch::Reloader.prepare!
true
end
end
end
此代码正确识别环境,不盲目包含Rails::ConsoleMethods。
来源-Github线程comment
【讨论】: