In BlogPost, Rails, Ruby

The Presenter Pattern With POROs for Rails Applications

When I first started making Rails applications, I ended up with views as shown in the below User Report Page code block after a while.

photodune-3999219-ruby-on-rails-s

I would check whether a user exists or not. If a user existed, I would display certain HTML markup. If you start trying to scale this type of logic over multiple lines, it becomes quite a mess to maintain.

Then I found out about the presenter pattern with POROs (Plain Old Ruby Objects).

What is a presenter pattern and why use it?

A presenter pattern takes your logic out of the views. It helps make your Rails views more maintainable.

Imagine if we started doing something more complicated such as displaying a different message if a user had an attached image file.

Hopefully, you are starting to see how messy the above can be to maintain. If we used a presenter pattern, our view code might look something like this:

Notice how much cleaner the view looks! No conditional logic is needed in the view. Because of this, it will be easier to maintain.

Step 1 – Make a BasePresenter class

As a first step, let’s make a BasePresenter class that will house common behavior.

Step 2 – Make a Presenter

Next, we make a presenter class that inherits from BasePresenter to encapsulate our “view” logic. In this example, I define a method called user_exists_message.

This method returns a message with some HTML markup regarding the existence of a User object.

Step 3 – Testing Your Presenter

Finally, if you want to add tests in RSpec, you need to instantiate a view instance of ActionController::Base.new.view_context.

Summary

Use the Ruby language to create presenter patterns to simplify code in your views. The presenter pattern will help you maintain your views over the life of a code base.

Recent Posts
oauth logo