[英]Rubocop: Assignment Branch Condition size for method is too high. How can I reduce the method?
This block of code:这段代码:
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
is returning the following rubocop offense:正在返回以下 rubocop 罪行:
Metrics/AbcSize: Assignment Branch Condition size for set_conversation is too high. [<1, 17, 5> 17.75/17]
I clearly understand the offense, but I'm having trouble refactoring the code to do the same task without adding too much unnecessary logic, especially because it's barely exceeding the suggested size.我清楚地理解这种冒犯,但我在重构代码以完成相同任务而不添加太多不必要的逻辑时遇到了麻烦,特别是因为它几乎没有超过建议的大小。 As a last resort, I may change the RuboCop config to ignore this block or to increase the limit, but first I want to try to solve it the intended way.
作为最后的手段,我可能会更改 RuboCop 配置以忽略此块或增加限制,但首先我想尝试以预期的方式解决它。
This is quite a complex lookup.这是一个相当复杂的查找。 One option is to extract this behaviour into a method on
Conversation
, eg Conversation.lookup(params[:conversation_id], current_api_user)
一种选择是将这种行为提取到
Conversation
上的方法中,例如Conversation.lookup(params[:conversation_id], current_api_user)
Another is to introduce a new service layer class or module, eg另一种是引入新的服务层类或模块,例如
LookupConversation.lookup(params[:conversation_id], current_api_user)
(there are likely other names you could choose to better reflect your application's business domain). (您可能可以选择其他名称来更好地反映您的应用程序的业务领域)。
Here's a start, which has the added benefit of setting @conversation
to a conversation object, rather than a boolean value:这是一个开始,它具有将
@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
Although further improvements can probably be made by introducing some meaningfully named method to represent the concept that a user is allowed in a conversation, for example:尽管可以通过引入一些有意义的命名方法来表示允许用户在对话中的概念来进行进一步的改进,例如:
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
This also allows Conversation#allowed_for?
这也允许
Conversation#allowed_for?
to be tested in isolation.进行隔离测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.