Ruby 命令行中快速查看函数源码

2013-02-14 20:28

Ruby 命令行中快速查看函数源码

by Aiur

at 2013-02-14 12:28:00

original http://www.udpwork.com/item/9244.html

如果要查看 ActiveRecord 的 update_attribute 函数的源代码,一个比较常见的方法是直接在 Rails 源码中搜索def update_attribute。博客The Pragmatic Studio介绍了一个更方便的技巧,在 Ruby 命令行中就能启动编辑器直接访问。

通过Object#method方法可以获得 update_attribute 方法的对象,而Method#source_location则返回这个方法定义的文件和位置。有了这个信息后,就能启动编辑器查看源代码了:

1
2
3
4
5
6
7
8
9
10
> method = User.first.method(:update_attribute)
  User Load (0.5ms)  SELECT `users`.* FROM `users` LIMIT 1
=> #<Method: User(ActiveRecord::Persistence)#update_attribute>

> location = method.source_location
=> ["/Users/wyx/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.2.11/lib/active_record/persistence.rb",
 177]

> `subl #{location[0]}:#{location[1]}`
=> ""

把这段代码封装成函数,加到 .pryrc 或者 .irbrc 中:

1
2
3
4
5
def source_for(object, method)
  location = object.method(method).source_location
  `subl #{location[0]}:#{location[1]}` if location && location[0] != '(eval)'
  location
end

如果要查看 User 的实例方法 update_attribute,可以直接在 pry / irb 中调用

1
source_for(User.first, :update_attribute)

如果要使用其他编辑器,得把subl #{location[0]}:#{location[1]}换成这个编辑器对应的命令行:

1
2
3
4
5
6
7
8
# TextMate
mate #{location[0]} -l #{location[1]}

# MacVim
mvim #{location[0]} +#{location[1]}

# Emacs
emacs {location[0]} +#{location[1]}

原文链接:http://pragmaticstudio.com/blog/2013/2/13/view-source-ruby-methods

⚓ Permalink

        <div style="margin-top:8px;padding:6px 0;border-top:1px solid #3cf">
            <div style="text-align:center;margin:16px 0;padding:6px;border:0px dashed #999;font-family:arial;font-size:26px;font-weight:bold">
<a href="http://www.udpwork.com/item/9244.html#review_form" title="不喜欢" style="text-decoration:none">
    <img src="http://www.udpwork.com//images/thumb_down24.gif" alt="">
    <span style="color:#f33">0</span>
</a>
   
<a href="http://www.udpwork.com/item/9244.html#review_form" title="喜欢" style="text-decoration:none">
    <img src="http://www.udpwork.com//images/thumb_up24.gif" alt="">
    <span style="color:#3c3">0</span>
</a>

udpwork.com 聚合 | 评论: 0 | 要! 要! 即刻! Now!