So I'm trying to take the right path here and understand how to solve this cop, this looks like a small piece of code IMO, why is it complaining?
moving the nested if-else doesn't change anything, any suggestions on how to solve this cop?
class WebPush::Register
include Interactor
# rubocop:disable Metrics/AbcSize
def call
user = Learner.find_by(id: context.user_id)
# return if existing
if user.web_push_subscription
context.subscription = user.web_push_subscription
else
subscription = WebPushSubscription.new(
endpoint: context.push_params[:endpoint],
auth_key: context.push_params[:keys][:auth],
p256dh_key: context.push_params[:keys][:p256dh],
learner: user
)
if subscription.save
context.subscription = subscription
else
context.error = subscription.errors.full_messages
context.fail!
end
end
end
# rubocop:enable Metrics/AbcSize
end
First, you need to understand how ABC is calculated. The nesting of conditionals does not affect ABC. RuboCop's warning output shows the calculation results:
The
<5, 28, 4>is your<Assignments, Branches, Conditionals>, as described in this article.The overall score is calculated like this:
sqrt(5^2 + 28^2 + 4^2) = 28.72The default maximum score for the cop is 17.
I've annotated your code below with the ABC scores for each line.
Every time
contextis referenced, the metric adds a B-point. This is becausecontextis not a local variable to thecallfunction, so the metric assumes that it's a new method-call every time.If you set the cop option: CountRepeatedAttributes: false (which I recommend), it will only add one B-point for all of the references to
contextcombined. That brings the ABC score down to19.1.In lieu of that, you can bring your score down by extracting the creation of
WebPushSubscriptioninto its own method like so:This will split the score up between the two methods. Note some additional ABC-saving strategies in
create_subscription, like assigningpush_paramsto a variable, and usingdigfor the nested hash accessors. The final score forcreate_subscriptionis between 12 and 16 depending on the cop options you use, andcallis between 6 and 8.Generally, all that's required to bring down ABC score is to refactor to smaller methods.