![](/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.