[英]Ruby / Rails meta programing, how to define instance and class methods dynamically?
[英]How to dynamically define all instance methods of class in module?
我要prepend
(或include
)某些模塊插入class
。 該模塊應該通過自定義動態定義class
定義的所有實例方法。 那可能嗎 ?
像這樣
Module M
klass_methods = get_instance_methods_of(classname)
// get_instance_methods_of is available to me.
// So, getting the methods is not a problem.
// But i have to pass class name
klass_methods.each do |m|
define_method m do
puts "from module"
super
end
end
end
Class C
prepend M
def some
puts "from class"
end
end
$ C.new.some
>> from module
>> from class
可能?
如果您想了解更多我想做的事情,可以在這里閱讀https://github.com/elabs/pundit/issues/244
我正在使用帶RoR的Ruby ruby 2.1.3p242
這是基於此答案的解決方案:
module M
def method_added(meth)
return if @recursing
@recursing = true
old_meth = instance_method(meth)
define_method(meth) do |*args, &block|
puts 'from module'
old_meth.bind(self).call(*args, &block)
end
@recursing = nil
end
end
class C
extend M
def some
puts "from class"
end
end
C.new.some
# from module
# from class
該解決方案使用method_added鈎子來攔截擴展類中的新方法,然后使用面向方面的代碼重新定義它們。
請注意,只有在extend M
行之后聲明的方法才會被攔截。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.