We spend so much time obsessing over where code belongs, except when talking about views. In Ruby on Rails, it seems to mostly be a conversation about business logic and the complexity that ensues.
Skinny Controllers, Fat Models!
Skinny Controllers, Skinny Models, Use Service Objects!
Something happens once that conversation ends: we move on, and our views get left out of the discussion. That doesn’t seem fair. After all, it’s Model – View – Controller.
I understand, though; I know a lot of full-stack developers (including myself) that don’t like to spend much time in the front-end.
We’re focused on writing testable, isolated, reusable, perfect code. We know how to refactor with all the design patterns. We’re ready to defend what we’ve written night and day. But, we’ll break all those rules to get out of writing front-end code as fast possible.
Clean Up Your Views
1. Get ActiveRecord Calls out of Your Views!
Start here. I consider ActiveRecord calls outside of business logic a code smell. I’ve written about this more in depth.
2 Write Helper Methods
Ruby on Rails couldn’t make this any easier for you. In fact, if you open up any Rails application right now, you’ll find the folder
app/helpers. Start small. Look for any Ruby code you’ve duplicated between multiple views and write a helper method for it. Once you’re happy with that, test that helper method.
3. Implement a View Model
A view model makes a lot of sense once you learn about it. Simply put, a view model is a model that is only concerned with presenting data to the user. My personal favorite view model implementation, currently, is the decorator pattern. You can start using it today in your Rails app with Draper.
Think about all the difference aspects of your code that don’t belong in a view: conditionals, database calls, logic, etc.
Soon, we’ll discuss more approaches for cleaning up our views in detail. Until then, try to write a helper or two. If you’re feeling wild, try to implement a view model!
Interested in More?
I'm an open book!
Drop me your email 👇🏻 and I'll share posts like this with you as I write them.