新手问题 可否知道其他 module 的__FILE__

est · 2014年09月22日 · 最后由 est 回复于 2014年09月23日 · 2053 次阅读

已知一个 module 可否知道对应源码路径在哪里?

比如

require 'active_record'

ActiveRecord.__FILE__
NoMethodError: undefined method `__FILE__' for ActiveRecord:Module
    from (irb):9

这样是不行的。

btw,python 可以。。。。比如import urllib2; urllib2.__file__

不能,除非你自己标个上去

#1 楼 @bhuztez 有没有对 VM 进行黑魔法使得可能的?

你找 module 里面的一个方法不就可以了?用 source_location

#2 楼 @est 这个是 Ruby 语义决定的吧。一个 Module 可以在多个文件里定义吧

pry 里可以这样:

[9] pry(main)> $  ActiveRecord::Base

From: /Users/hooopo/.gem/ruby/2.1.2/gems/activerecord-3.2.18/lib/active_record/base.rb @ line 333:
Class name: ActiveRecord::Base
Number of monkeypatches: 20. Use the `-a` option to display all available monkeypatches
Number of lines: 384

class Base
  ##
  # :singleton-method:
  # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
  # which is then passed on to any new database connections made and which can be retrieved on both
  # a class and instance level by calling +logger+.
  cattr_accessor :logger, :instance_writer => false

#3 楼 @marventu 可否给个例子?多谢。

#6 楼 @est 如果想查看方法的源码位置,可以在 Method 对象上,调用 source_location 方法:

ActiveRecord::Base.method(:find).source_location

#7 楼 @zhangyuan 这个好。多谢。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号