Rails Presenters

Post on 24-May-2015

83 views 1 download

Tags:

description

A quick run down on the presenter pattern in rails, code for the talk is here https://github.com/ridget/presenters_app

Transcript of Rails Presenters

PRESENTERSwith a guest appearance from decorators

HI

• tomridge2@gmail.com

• @tjridge

• github.com/ridget

LETS BUILD AN APP

VIEW RELATED LOGIC

• welp

LETS PUT IT IN A HELPER!

HELPERS AREN’T AWESOME

• at least for this task

• they share a global namespace

• aren’t a very oo way of solving the problem

• great for shared logic that doesn't relate to the object. Use sparingly

I KNOW MODELS!

• also nope

• All these if conditions relate to the display of data

• Don’t overload your model with that level of responsibility

ENTER PRESENTERS

• Presenters are a simple class with knowledge of the model and the view.

• Not a stretch to call them a ViewModel

PURPOSE

• Presenters help to achieve adherence to SRP

• A Presenter’s purpose is a decorator who has the job of massaging the decorated object into a ui/view friendly manner.

DECORATOR?

• Taking one object and adding, replacing or extending its behaviour, whilst allowing access to the underlying objects methods.

PRESENTERS VS DECORATORS

• A decorator isn’t always a presenter, but a presenter is always likely to be a decorator.

END RESULT

• This is more in line with a decorator approach

• We just delegate to the underlying object

MULTIPLE OBJECTS?

• ensure you delegate methods to the underlying objects

MULTIPLE RECORDS?

• Just create a wrap method to instantiate your presenter/decorator across multiple records.

OTHER OPTIONS?

• Draper

• Great for when things start getting more complex

OTHER VALUE POINTS

• Easy-ish to test

• less conditionals in your views

• happier designers/front end developers

CONS

• More objects == harder to learn the codebase

• Don’t introduce them until you need to.

GREAT RESOURCES

• Railscasts - draper and presenters from scratch (pro)

• http://new-bamboo.co.uk/blog/2013/04/17/rails-presenters-skinny-everything

• http://robertomurray.co.uk/blog/2014/decorators-presenters-delegators-rails/

QUESTIONS?