Ruby | 部屋とYシャツと src_location と override と ネイティブメソッド と eval と singleton method と私
概要
src_location でメソッドのソースコードのファイル名と行番号を取得する際のサンプル集です。
詳細
下記の例を確認します
メソッドの定義例 | 結果 |
---|---|
String クラスを継承して shuffle メソッドを実装 | 継承先のファイル名、行数 |
String クラスを継承して sample メソッドを実装(define_method を利用) | 継承先のファイル名、行数 |
String クラスを継承して upcase メソッドをオーバーライド | 継承先のファイル名、行数 |
ネイティブなメソッド String#downcase メソッド | nil を取得(src_location の仕様) |
eval でメソッドを実装 | (eval), 1 という結果が返却される |
シングルトンメソッドを実装 | シングルトンメソッドの定義場所を取得 |
モジュールをinclude | includeしたモジュールの定義場所を取得 |
自作 gem tbpgr_utils の Array#to_table メソッド | gem のファイルパスと行数が正常に返却される |
サンプルコード
src_location.rb
require 'tbpgr_utils'
module Hogeable
def hogeable
"hogeable"
end
end
class ShuffleString < String
include Hogeable
def shuffle
chars.shuffle.join('')
end
define_method :sample do|chars.sample
end
# override
def upcase
downcase
end
eval 'def hoge;print "hoge";end'
end
ss = ShuffleString.new('hoge')
def ss.hage
"hage"
end
10.times {print ss.shuffle, "\n"}
10.times {print ss.sample, "\n"}
puts ss.hoge
puts ss.hage
bulk_puts_eval binding, <<-EOS
ss.method(:shuffle).owner
ss.method(:shuffle).source_location
ss.method(:sample).owner
ss.method(:sample).source_location
ss.method(:upcase).owner
ss.method(:upcase).source_location
ss.method(:downcase).owner
ss.method(:downcase).source_location
ss.method(:hoge).owner
ss.method(:hoge).source_location
ss.method(:hage).owner
ss.method(:hage).source_location
ss.method(:hogeable).owner
ss.method(:hogeable).source_location
[[]].method(:to_table).owner
[[]].method(:to_table).source_location
EOS
__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval
to_table
https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
$ ruby src_location.rb
ehgo
gohe
oghe
ehog
geoh
ehog
hoeg
ohge
geho
heog
o
h
h
g
o
h
h
g
e
o
hoge
hage
ss.method(:shuffle).owner # => ShuffleString
ss.method(:shuffle).source_location # => ["src_location.rb", 3]
ss.method(:sample).owner # => ShuffleString
ss.method(:sample).source_location # => ["src_location.rb", 7]
ss.method(:upcase).owner # => ShuffleString
ss.method(:upcase).source_location # => ["src_location.rb", 12]
ss.method(:downcase).owner # => String
ss.method(:downcase).source_location # => nil
ss.method(:hoge).owner # => ShuffleString
ss.method(:hoge).source_location # => ["(eval)", 1]
ss.method(:hage).owner # => #<Class:#<ShuffleString:0x00000600b746d8>>
ss.method(:hage).source_location # => ["src_location.rb", 20]
ss.method(:hogeable).owner # => Hogeable
ss.method(:hogeable).source_location # => ["src_location.rb", 4]
[[]].method(:to_table).owner # => Array
[[]].method(:to_table).source_location # => ["/path/to/gems/tbpgr_utils-0.0.150/lib/open_classes/array/to_table.rb", 16]