[英]Ruby/Rails: alias_method practices
我試圖覆蓋Rails的“fields_for”方法,我目前正在做如下:
module ActionView::Helpers::FormHelper
include ActionView::Helpers::FormTagHelper
alias_method :original_fields_for, :fields_for
def fields_for(<my arguments>)
# Some extra stuff
# ...
output.safe_concat original_fields_for(<my other arguments>)
end
end
功能很好,但我開始懷疑我使用alias_method並不是最優雅的。 最特別的是,如果我要將此功能打包到gem中,並且還有另一個寶石覆蓋了fields_for,我是否會想到我的新fields_for或備用fields_for會被跳過?
假設是這樣,將一些額外的功能用於現有的rails方法的正確方法是什么?
干杯...
這看起來就像alias_method_chain
的意思(雖然我不知道它是否適用於模塊 - 只在AR :: Base上使用它)
你只是這樣做
module ActionView::Helpers::FormHelper
include ActionView::Helpers::FormTagHelper
alias_method_chain :fields_for, :honeypot
def fields_for_with_honeypot(<my arguments>)
# Some extra stuff
# ...
output.safe_concat fields_for_without_honeypot(<my other arguments>)
end
end
有趣的想法這樣做到fields_for
,但它應該工作。
關於a_m_c你應該知道一個小小的爭議 - 這篇文章總結得很好http://erniemiller.org/2011/02/03/when-to-use-alias_method_chain/
在這種情況下,我認為你不能使用super
因為你想修改form_for而不修改調用代碼/視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.