广州葆元健康生物科技有限公司


Ruby实现命令行中查看函数源码的方法

网络编程 Ruby实现命令行中查看函数源码的方法 06-21

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

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

> 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 中:

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 中调用

source_for(User.first, :update_attribute)

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

# TextMate

mate #{location[0]} -l #{location[1]}

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

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

Ruby中的public、private、protected区别小结
重点关注private与protectedpublic默认即为public,全局都可以访问,这个不解释privateC++,private意为privatetothisclass,但是Ruby中意为privatetothisinstance.意思是:C++中

Java 版的 Ruby 解释器 JRuby 1.7.14 发布
JRuby1.7.14发布,此版本现已提供下载:http://www.jruby.org/downloadJRuby1.7主要是为了兼容Ruby1.9.3版本,改进记录如下:解决了30个issues修复了Jar文件源潜在的

Rails bundle命令安装mysql gem包出错的解决方法
解决Railsbundle安装不上mysqlgem包的问题环境ubuntu12.04ruby-2.1.1首先新建一个的一个项目,在该项目上执行bundleinstall提示...Makesurethatgeminstallmysql2-v'0.3.16';succee


编辑:广州葆元健康生物科技有限公司

标签:编辑器,方法,命令行,源代码,函数