在Rails中,假设文件已经加载,如何从控制台调用
my_method
?# some_file.rb
class MyClass < ApplicationController::Base
def my_method(args)
my_method
?# some_file.rb
class MyClass < ApplicationController::Base
def my_method(args)
另一种非常简单的方法是使用一个 ApplicationController
实例本身。
ApplicationController < ActionController::Base
def example
"O HAI"
end
end
然后在控制台中,你可以执行以下操作:
>> ApplicationController.new.example
这将输出以下内容:
O HAI
当然,这种方法有一个限制,无法访问正常请求中的所有内容,例如request
对象本身。如果您需要此功能,可以像Patrick Klingemann建议的那样使用调试器...我个人推荐使用Pry:
对您来说可能太晚了,但希望能帮到将来的某个人。
使用调试器:
在你的Gemfile
中添加:
gem 'debugger'
然后从终端输入:
> bundle
> rails s --debugger
class WidgetsController < ApplicationController
def index
debugger
@widgets = Widget.all
respond_with @widgets
end
end
然后将浏览器指向:http://localhost:3000/widgets
,该页面不会完成加载。返回运行服务器的终端,您将进入一个交互式调试会话,可以运行:my_method
虽然这不是所问的问题,但你也可以像使用debugger
一样使用pry
gem进行调试。
在Gemfile
中添加:
gem "pry"
gem "pry-remote"
gem "pry-stack_explorer"
gem "pry-debugger"
def myMethod
binding.pry
# some code
end
完成了!
当你运行你的方法时,页面处理将会在binding.pry
处冻结,pry将接管提示符。每个新步骤输入n
,并在“实时”中玩弄可以打印的变量(只需键入它们)!