如何獲取同一方法內的方法的整個命名空間定義路徑?
使用此示例可以簡化問題:
module Parent
module Child
def self.get_complete_namespace
this_path = ???
puts this_path.to_s
end
end
end
Parent::Child.get_complete_namespace
#=> "Parent::Child.get_complete_namespace"
因此,要放置或列印出這個字串“Parent::Child.get_complete_namespace”,使用 self super o 類似的“this_path”變數值是什么?
uj5u.com熱心網友回復:
我不知道任何現有的功能,盡管您可以很容易地使用__callee__(or __method__)創建一個
module Parent
module Child
def self.get_complete_namespace
m = method(__callee__)
"#{m.receiver.name}.#{m.name}"
end
end
end
Parent::Child.get_complete_namespace
#=> "Parent::Child.get_complete_namespace"
一些使用說明:
__callee__并且__method__通常會回傳相同的符號。如果方法是別名,則__callee__回傳被呼叫的方法名稱,而__method__將回傳定義的方法名稱。- 對于類/模塊方法,您需要使用
m.receiver. 對于實體方法,您需要使用m.owner. 請參閱方法。
類示例:
module Parent
class Child
def self.get_complete_namespace
m = method(__callee__)
"#{m.receiver.name}.#{m.name}"
end
def get_complete_namespace
m = method(__callee__)
"#{m.owner.name}.#{m.name}"
end
alias_method :complete, :get_complete_namespace
end
end
Parent::Child.get_complete_namespace
#=> "Parent::Child.get_complete_namespace"
Parent::Child.new.get_complete_namespace
#=> "Parent::Child.get_complete_namespace"
Parent::Child.new.complete
#=> "Parent::Child.complete"
編輯 - 單行版本:
def self.get_complete_namespace
method(__callee__).instance_eval { "#{receiver.name}.#{name}" }
end
uj5u.com熱心網友回復:
你可以寫get_complete_namespace如下。
module Grandparent
module Parent
module Child
def self.get_complete_namespace
"#{Module.nesting.first}::#{__method__}"
end
end
end
end
Grandparent::Parent::Child.get_complete_namespace
#=> "Grandparent::Parent::Child.get_complete_namespace"
請參閱Module::nesting和Kernel#方法。
如果該方法的操作線Grandparent::Parent::Child::get_complete_namespace是
Module.nesting
該方法將回傳
[Grandparent::Parent::Child, Grandparent::Parent, Grandparent]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460552.html
