Rails Presenters

20
PRESENTERS with a guest appearance from decorators

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

Page 1: Rails Presenters

PRESENTERSwith a guest appearance from decorators

Page 2: Rails Presenters

HI

[email protected]

• @tjridge

• github.com/ridget

Page 3: Rails Presenters

LETS BUILD AN APP

Page 4: Rails Presenters

VIEW RELATED LOGIC

• welp

Page 5: Rails Presenters

LETS PUT IT IN A HELPER!

Page 6: Rails Presenters
Page 7: Rails Presenters

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

Page 8: Rails Presenters

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

Page 9: Rails Presenters

ENTER PRESENTERS

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

• Not a stretch to call them a ViewModel

Page 10: Rails Presenters

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.

Page 11: Rails Presenters

DECORATOR?

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

Page 12: Rails Presenters

PRESENTERS VS DECORATORS

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

Page 13: Rails Presenters

END RESULT

• This is more in line with a decorator approach

• We just delegate to the underlying object

Page 14: Rails Presenters

MULTIPLE OBJECTS?

• ensure you delegate methods to the underlying objects

Page 15: Rails Presenters

MULTIPLE RECORDS?

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

Page 16: Rails Presenters

OTHER OPTIONS?

• Draper

• Great for when things start getting more complex

Page 17: Rails Presenters

OTHER VALUE POINTS

• Easy-ish to test

• less conditionals in your views

• happier designers/front end developers

Page 18: Rails Presenters

CONS

• More objects == harder to learn the codebase

• Don’t introduce them until you need to.

Page 19: Rails Presenters

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/

Page 20: Rails Presenters

QUESTIONS?