LoginSignup
40
39

More than 5 years have passed since last update.

Rubyでクラスがどこで定義されているか調べる

Last updated at Posted at 2013-09-02

Method#source_location はあるが、Class#source_location はない。そもそもクラス定義が複数のファイルにわたっていることも多いので、あったとしてもたいして意味はない。

それでは、あるクラスの(インスタンス)メソッドがどこで定義されているか調べたらどうか?

Rails.class.instance_methods(false).map { |s| Rails.method(s).source_location }.compact.map { |x| x[0] }.sort.uniq.map { |x| x.sub(/\A.*2.0.0./, '') }
=> ["pp.rb",
 "psych/core_ext.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/aliasing.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/anonymous.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/attr_internal.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/attribute_accessors.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/delegation.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/deprecation.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/introspection.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/method_names.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/qualified_const.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/reachable.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/remove_method.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/module/synchronization.rb",
 "gems/activesupport-3.2.11/lib/active_support/core_ext/object/duplicable.rb",
 "gems/activesupport-3.2.11/lib/active_support/dependencies.rb",
 "gems/activesupport-3.2.11/lib/active_support/deprecation/method_wrappers.rb",
 "gems/debugger-1.6.0/lib/ruby-debug-base.rb",
 "gems/liquid-2.5.0/lib/liquid/module_ex.rb",
 "gems/rake-0.9.2.2/lib/rake/ext/core.rb",
# (snip)

なんだかワサワサ出てきた。

参考文献: Rubyのメソッドを数えましょう♫

40
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
39