'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:

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 refactorizing the code to do the same task without adding too much unnecesary logic. Especially because it's barely surpassing the suggested size. As a last resource, 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.



Solution 1:[1]

This is quite a complex lookup. One option is to extract this behaviour into a method on Conversation, e.g. Conversation.lookup(params[:conversation_id], current_api_user)

Another is to introduce a new service layer class or module, e.g.

LookupConversation.lookup(params[:conversation_id], current_api_user)

(there are likely other names you could choose to better reflect your application's business domain).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy Waite