![](/img/trans.png)
[英]Rubocop error: Assignment Branch Condition size for a function is too high. How can I decrease this?
[英]Rubocop: Assignment Branch Condition size for method is too high. How can I reduce the method?
這段代碼:
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
.match.origin_target.user_id == current_api_user.id ||
Conversation.find(params[:conversation_id])
.match.end_target.user_id == current_api_user.id
head :forbidden if @conversation == false
end
正在返回以下 rubocop 罪行:
Metrics/AbcSize: Assignment Branch Condition size for set_conversation is too high. [<1, 17, 5> 17.75/17]
我清楚地理解這種冒犯,但我在重構代碼以完成相同任務而不添加太多不必要的邏輯時遇到了麻煩,特別是因為它幾乎沒有超過建議的大小。 作為最后的手段,我可能會更改 RuboCop 配置以忽略此塊或增加限制,但首先我想嘗試以預期的方式解決它。
這是一個相當復雜的查找。 一種選擇是將這種行為提取到Conversation
上的方法中,例如Conversation.lookup(params[:conversation_id], current_api_user)
另一種是引入新的服務層類或模塊,例如
LookupConversation.lookup(params[:conversation_id], current_api_user)
(您可能可以選擇其他名稱來更好地反映您的應用程序的業務領域)。
這是一個開始,它具有將@conversation
設置為對話對象而不是布爾值的額外好處:
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
user_ids = @conversation.match.tap { |m| [m.end_target.user_id, m.origin_target.user_id] }
head :forbidden if user_ids.include?(current_api_user.id)
end
盡管可以通過引入一些有意義的命名方法來表示允許用戶在對話中的概念來進行進一步的改進,例如:
class Conversation < ApplicationRecord
def allowed_for?(user)
match
.tap { |m| [m.end_target.user_id, m.origin_target.user_id] }
.include?(user.id)
end
end
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
head :forbidden conversation.allowed_for?(current_api_user)
end
這也允許Conversation#allowed_for?
進行隔離測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.