[英]How to get the name of the calling alias method?
我有一個名為link_to_admin
方法,然后我將另一個名為simple_link_to
方法別名
def link_to_admin(name,url,options={})
# My stuff here
link_to(name,url,options)
end
alias_method :simple_link_to, :link_to_admin
在這里我link_to_admin
一個問題,如果我調用link_to_admin
,我想將值打印到<li>
標簽中
防爆。
def link_to_admin(name,url,options={})
# My stuff here
menu = ""
menu << "<li> #{link_to(name,url,options)}</li>"
menu.html_safe
end
如果我調用simple_link_to
不需要<li>
標簽。 所以目前我正在傳遞一個像li_required
這樣的options
然后在我的方法中檢查條件。 這是完美的,我知道這是正確的方法。
def link_to_admin(name,url,options={})
menu = ""
menu << options[:li_required] ? "<li> #{link_to(name,url,options)}</li>" : link_to(name,url,options)
menu.html_safe
end
但是,在我嘗試找到像simple_method
或link_to_admin
這樣的調用方法simple_method
,我試過:
1.__method__
2.caller[0]=~/`(.*?)'/
這沒有按預期工作。
我在layout
調用simple_method
或link_to_admin
方法,因此__method__
始終只返回link_to_admin
。
但是caller[0]=~/
/(。*?)'/ means, it's returning layout path and if I am calling from any other
if am calling from
布局if am calling from
means, it's returning layout path and if I am calling from any other
幫助器or
類means, it's returning layout path and if I am calling from any other
則意味着它返回當前方法。
任何其他方式是檢查方法名稱。
我知道這不是一個好問題,任何人都可以告訴我任何其他方式。
注意: - 我創建了alias_method僅用於命名轉換。 除了添加<li>
標簽,我沒有做任何事情。
不僅在這里,我還有很長一段時間的懷疑。 我知道我可以再定義一種方法,我可以做到。
離開我的場景,一般我想知道這個答案。
使用__callee__
而不是__method__
將獲取正在運行的別名的名稱。
我建議,不要依賴於方法名稱和分支(對於任何方法名稱重構都會變得很脆弱,顯然更復雜,等等),您只需將方法分解為將共同邏輯抽象為共享方法。
這是我寫它的方式:
def simple_link_to(name, url, options = {})
# shared_link_to(name) ... or whatever
link_to(name, url, options)
end
def link_to_admin(name, url, options = {})
# shared_link_to(name) ... or whatever
content_tag(:li) do
simple_link_to(name, url, options)
end
end
private
def shared_link_to(name)
# do whatever is common
end
注意:我已經猜到你有一些常見的代碼,你想要抽象出一些方法(我稱之為shared_link_to
)......但是你需要用那個部分做你需要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.