ruby - Dynamically define a method inside an instance method -
i working on project of context-oriented programming in ruby. , come problem:
suppose have class klass:
class klass def my_method proceed end end i have proc stored inside variable impl. , impl contains { puts "it works!" }.
from somewhere outside klass, define method called proceed inside method my_method. if call klass.new.my_method, result "it works".
so final result should that:
class klass def my_method def proceed puts "it works!" end proceed end end or if have other idea make call of proceed inside my_method working, it's good. proceed of method (let's my_method_2) isn't same my_method. in fact, proceed of my_method represent old version of my_method. , proceed of my_method_2 represent old version of my_method_2.
thanks help
disclaimer: you doing wrong!
there must more robust, elegant , rubyish way achieve want. if still want abuse metaprogramming, here go:
class klass def self.proceeds @proceeds ||= {} end def def_proceed self.class.proceeds[caller.first[/`.*?'/]] = proc.new end def proceed *args self.class.proceeds[caller.first[/`.*?'/]].(*args) end def m_1 def_proceed { puts 1 } proceed end def m_2 def_proceed { puts 2 } proceed end end inst = klass.new inst.m_1 #⇒ 1 inst.m_2 #⇒ 2 what in fact need, module#prepend , call super there.
Comments
Post a Comment