Refactoring Untested Case Statements in Ruby

3
343

I recently came across a small Sinatra app called PixelHoldr that generates placeholder images for your site based on the options you pass in through the url. This is a handy little addition to a web developers arsenal so I decided to take a look at the code.

There isn’t a lot of code necessary to run the app but there was a case statement that jumped out at me immediately. The Gist below shows the method that will be the example for this post.

I also gave it a quick check on Code Climate to see if the the score is improved once the method is refactored.

pixelholdr-get-hex-start

 

After poking around the PixelHoldr source, I found that there were no tests so that was first on the agenda. I also wanted to move the functionality into a class so that the functionality was encapsulated in an object with a name that represents its function.

I used TDD to drive the class creation but because there were no existing tests, I simply copied the get_hex method directly into the class and set up an initializer that will accept the color parameter.

At this point, I worked backwards to create tests that would validate the current functionality.  This would give us the tests needed to refactor the logic within the method. It was also during the test creation that I changed the get_hex method name to generate_color because that seemed to better convey the action being performed.

Now that the tests are in place, the method can be refactored without worrying that bugs are being introduced.  I’ll save the step by step at this point because the changes are easy to read.  The refactored class is shown in the gist below.

After pushing the class up to Github and running it through Code Climate, you can see that the end result gives a much better score.

after-pixelholder-get-hex-refactor

 

See the associated files for this refactor on Github:  PixelHoldrRefactor

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here