分享 在 console 中直接开启编辑器查看源码

lgn21st · February 14, 2013 · Last by kgen replied at February 20, 2013 · 5587 hits
Topic has been selected as the excellent topic by the admin.

http://pragmaticstudio.com/blog/2013/2/13/view-source-ruby-methods

具体做法是在 .irbrc 中添加一个 helper method

def source_for(object, method)
  location = object.method(method).source_location
  # `mate #{location[0]} -l #{location[1]}` 
  # `mvim #{location[0]} +#{location[1]}`
  `subl #{location[0]}:#{location[1]}` if location # for Sublime Text
  location
end

然后再 Rails console 中就可以直接打开编辑器查看方法定义的 source code 了 比如查看 Person 实例的 update 方法:

source_for(Person.new, :update)

如果用 pry, 可以直接 edit Person#update

#1 楼 @luikore pry 简直强大到无以复加!而且就在 Gemfile 里面添加一行就 ok 了。

gem 'pry-rails'

顺便推荐一篇文章:Pry Everywhere

#2 楼 @lgn21st 嗯嗯!而且 vim 里用 slime 就能和 pry 之间跳来跳去超爽

断点调试最强大,可以结合 proxy 做一个类似 fiddler 的东东?

自从用了 better_errors + binding_of_caller,让 pry 也退休了。

@luikore 在 vim 怎么用的呢?有参考资料吗?

#6 楼 @kgen 传说中 better_errors 很棒,一会我也要试试。

#6 楼 @kgen 这个加断点要 raise 才行了

#8 楼 @ery 特别是加了 binding_of_caller 居然可以在浏览器中 debug,帅极了

#9 楼 @doitian 嗯,加断点的确没有 pry 方便,要手动加 raise

#10 楼 @kgen 不过我猜测,在查找单元测试的报错原因的时候,还是需要依靠 pry。

#12 楼 @ery 单元测试颗粒极小,基本上出错就知道原因了,我很少 Debug 单元测试

You need to Sign in before reply, if you don't have an account, please Sign up first.