Rubyのクラスメソッドでのmethod_missing
まずmethod_missingを特異クラスに仕込む
class Sample class << self def method_missing(method, *args) p "miss: #{method}" end end end Sample.hoge => # => miss: hoge Sample.hoge => # => miss: hoge
そこでdefine_methodでメソッド足してみる
当然、特異クラス内でmodule_eval呼んでその中でdefine_methodよぶんだから当然これでいけるとおもったけど、、、
class Sample class << self def method_missing(method, *args) p "miss: #{method}" module_eval do define_method method do p "defined: #{method}" end end end end end Sample.hoge => # => miss: hoge Sample.hoge => # => miss: hoge(あれ?)
無理みたい
なかなか公式なdocumentが見つからない。。
ふとおもいったって試してみると
Sample.new.hoge => # => defined: hoge
(・_・?)...ン?。。。
インスタンスメソッドが足されてる( ̄Д ̄;)
ならここで特異メソッド開いて足してみる
class Sample class << self def method_missing(method, *args) p "miss: #{method}" (class << self; self; end).module_eval do define_method method do p "defined: #{method}" end end end end end Sample.hanako # => miss: hoge Sample.hanako # => defined: hanako
いけた!
なんで、特異クラスを開かないといけないかはわからないけど、とりあえず解決。