Extracting the InviteRedeemer class from the Invite model in Discourse – Part 3


The results of previous post left us in decent shape to finish up the refactoring of the InviteRedeemer#redeem method.  The gist below shows the starting point for this portion of the refactoring. The private methods are left out for brevity.

The first thing to tackle is the multiple assignments to the result variable.  The first change is to replace the nil assignment in ‘result = nil‘ with a call to a new method named invited_user.

By adding the method above, the else branch of the if clause can be removed. In order to make sure everything still works as expected, the tests are run and everything is green.

The second benefit of this addition is that it is no longer necessary to pass the result to the methods because the user can be retrieved from the invited_user method from the method itself.

The next step is to replace the ‘mark_invite_redeemed == 1‘ line with something that has a name that is more explanatory. To do this, a private method named invite_was_redeemed?.

After the change above, move the steps inside the if clause into their own private method named process_invitation.  

The redeem method now looks like the gist below.

At this point, things are looking really good …except for the repeated references to result. But upon taking a better look, it becomes obvious that we can rearrange things a little bit to contain all of the user retreival functionality in one place.

The changes above mean that the get_invited_user method will first check for the an existing user and then create a new user only if one doesn’t exist.

By keeping the user retrieval inside one method and combining it with the lazy initialization of invited_user, it means that we can remove result from the redeem method completely which gives us our final result.

A final check on Code Climate shows that the score for the Invite model has gone from C to A.


This change was submitted to Discourse and was merged as pull request #927


Please enter your comment!
Please enter your name here