簡體   English   中英

使控制器代碼在Rails中變干

[英]Making controller code dry in rails

我有兩個具有更新操作的控制器。 這兩個動作都有相似的代碼,我很困惑如何刪除重復並使之變干。 代碼環境在這一方面顯示出重復問題。 這是詳細信息。

Controller 1:
respond_to do |format|
  if @business_profile.update(business_profiles_params)
    format.html { redirect_to settings_path, notice: t('setting_successful_message') }
  else
    format.html { redirect_to settings_path, alert: t('setting_failure_message')
  end
end
Controller 2:
respond_to do |format|
  if @contact.update(contact_params)
    format.html { redirect_to contacts_path, notice: t('contact_successful_message') }
  else
    format.html { redirect_to contacts_path, alert: t('contact_failure_message')
  end
end

所以我希望這些相似的內容合而為一。

它們都缺少if塊的end ,並且第一個可能在stting_failure_message輸入錯誤。 兩者在else塊中都缺少右大括號( } 可能還有更細微的問題。

在擔心諸如從兩個控制器更新方法中提取要調用的共享方法之類的優化之前,請先運行代碼並通過控制器測試。 就其價值而言,當前的重復程度對我而言是正確的,體現在局部的表達方式以及更改與抽象之間的獨立性,以消除重復數據。 請看以下問題,以更一般性地討論DRY控制器中的最佳實踐在Ruby on Rails中的控制器之間重用代碼的最佳實踐。

而在這一項中評分最高的答案就是您正在考慮的提取的成本/收益

Rails 3.2中的DRY控制器

如果計划使用Flash消息進行響應並重定向到,請檢出響應者 gem,特別是FlashResponder( https://github.com/plataformatec/responders#flashresponder )和CollectionResponder( https://github.com/plataformatec/responders#collectionresponder )經常執行索引操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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