Refactoring a Rails controller

I have been contributing a little bit to a project called WikiCausality. This project basically tries to set up a webpage that shows links between environmental issues and suggests causal links so it’s easier to depict this causal links.

Anyway, back to the code, what I have done here is to refactor the method create from issues_controller.rb. What this method does is to create a new issue, link issues that already exist, and accept suggestions, create an issue for them, and link them. Quite a lot for just a method in my opinion. So what I did was to clear this and try to remove as much duplication as I could.

I think one of the main problems here was that it is not recommended to use an instance variable in your controller or view unless you created that instance variable. I tried to follow this as closely as possible and the result worked.

Still, the endless switch (case) statement drove me a little bit crazy but I found no way of translating the enormous list of ifs to anything easier to debug and more importantly, with less duplication. I chose to extract everything into two switch mainly because switches are implemented with an indexed branch table in Ruby – i.e  its quite faster. Take a close look at this one and help me to refactor it!

Here’s the original file:

And this is the refactored one: