Removing Duplication From the Post Model in Discourse


Discourse made a big splash a few months back when the project was first revealed.  Being that it’s such a well known codebase in the Ruby community I decided to spend some time doing some minor refactoring to get my feet wet.

After looking at the scores on Code Climate, the Post model seemed like a good place to start.  The code analysis showed that a few methods were increasing the duplication score.

Post Duplication
Post Duplication

The code in question are the three methods below:

At first glance, the repetitive check on the user jumped out at me.  This is easily solved by introducing a private method that does the check and has a name that clearly conveys the intention.

After the extraction, the checks in the methods were changed to call the private method.

With the user check taken care of, the next step is to replace the calls to errors.add with a method that simplifies the addition of the errors.  To do this, I added another private method.

With the new private method to add errors in place, we now have everything we need to finalize our refactoring.  Many of the methods that were flagged in the duplication check are now one line and have calls to method names that make it easier to grasp what is being accomplished.

After this refactoring, another check was run through Code Climate and the result is that the duplication is now removed.


This change was pushed to Discourse and accepted in commit a866463.


Please enter your comment!
Please enter your name here