Presenters in Ruby on Rails
Ruby on Rails is all about Model View Controller (MVC). This is a web development technique to separate database, html and code. This is a smart idea since these three fields require very different things. Usually this separation works well. Sometimes though I need a fourth distinction. And I use a Presenter.
Update: .autospec file added
I have used Presenters (and Conductors, which are similar in many ways) for years and I keep wondering why the Rails team doesn’t include them by default. Every app I build has a need for them. Usually this revolves around an index page that has lots of different elements on it.
For my latest presenter, I needed to gather no less than eight different categories, posts and page collections. Without a presenter, this would mean eight different variables in the controller, and sending all these instance variables to the view. No way around that since all elements must be present on the page, one way or another.
But to keep the controller clean and the intented logic clear, I proceeded to put these eight variables into a presenter. Now, instead of 8 variables I ended up with 8 methods. This is a lot cleaner, since it allowed me to spec every method individually and re-use shared code. Then in the controller I initialize just this one presenter and send that to the view. Result: controller is squeeky clean, view has only one instance variable to deal with and presenter has eight different, but small methods.
If you haven’t already, check out this post. It’s this pattern I use most often since it’s the cleanest way possible.
Speccing
To keep RSpec in sync with the new directory full of presenters, create a .autospec file in the root of your project and add this:
Autotest.add_hook :initialize do |at|
at.add_mapping(%r%^app/presenters/(.*)\.rb$%) { |_, m|
at.files_matching %r%^spec/presenters/#{m[1]}_spec.rb$%
}
end
No comments yet.