簡體   English   中英

如何獲取調用別名方法的名稱?

[英]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_methodlink_to_admin這樣的調用方法simple_method ,我試過:

1.__method__
2.caller[0]=~/`(.*?)'/

這沒有按預期工作。

我在layout調用simple_methodlink_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幫助器ormeans, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM