litany against fear

coding with spice ¤ by nick quaranto

Rails AntiPatterns Notes

published 19 Nov 2008

Part of my series of notes from the Professional Ruby Conference. See them all here.

This talk is from Chad Pytel and Tammer Saleh from Thoughtbot.

They’re gonna talk about things that they’ve seen that have gone wrong in the Rails world. It’s not gonna teach you to do TDD. It’s gonna show you how to fix code better.

Move code from controller to the model. 14 lines is TOO long for the create action. Might be crazy but you need to keep your guard up. Some crazy stuff is going on in this method. Transaction, catching an exception too. Refactored so it’s a bit smaller, but not ideal yet. Refactor by identifying parts of code that are identical. Try to weed out unnecessary code too. Use AR callbacks when you can, a LOT easier. DO WHAT YOU MEAN. Have expressive callback names. Constantly check for code that isn’t needed. Don’t violate the Law of Demeter…keep things DRY and look into the rule when you can. Use conditional callbacks in Rails 2.1 to remove even MORE code. Once again, push actions down into callbacks when possible. Get rid of transactions if you can. Only rescue exceptions if they are truly exceptional!

Putting too much domain knowledge in the controllers is BAD. They move state checking out of the controller and into the model by defining a hash and dynamically creating methods to check the state. Tackle large refactoring iteratively! Shove business logic into the model. DRY DRY DRY. Use named scopes instead of having complex finders in your controllers.

User Roles. See them all the time in apps. Ugly, messy, thoughtless code. Instead of having a role model, use boolean fields if you only have a small number of roles. If more than that, use has_many and not HABTM. Don’t build beyond the requirements and don’t jump to models prematurely.

Bad code happens to good people. This was all production code that they definitely wrote, but looked like crap 3-6 months down the line. The real lesson is to always be refactoring.



code (2) gaming (3) git (9) internet (5) prorubyconf (25) railsconf (17) ruby (10) windows (3)