Presenter and Decorator in Rails

Embed Size (px)

Citation preview

Presenter & DecoratorIn Rails

Decorator

What is Decorator in Rails?

A decorator is a design pattern. Its intent, as described in Design Patterns by the Gang of Four is:

> Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Why do we use Decorator?

Refactoring for SRP (Single Responsibility Principle)

Extend behaviors of an object

Try out #1

I have a coffee class which has #cost method.

Class Coffee def cost 2 endend

coffee = Coffee.new()coffee.cost#=> 2

What if I want to add sugar or milk? Assume sugar price is 0.2 and Milk is 0.4

How to implement Decorator?

There is a great post by Dan Croak on how to implement Decorator in rails.

http://robots.thoughtbot.com/post/14825364877/evaluating-alternative-decorator-implementations-in

When to use Decorator?

When an object knows too much.

When a group of methods describe a possible meaning of behavior

When want to extend behavior of an object

When fully understand Decorator

Presenter

What is Presenter in Rails?

A form of Decorator

A bridge between the model and view in presentation logic

Why do we use Presenter?

To cleanup views by moving aways all the logic

To keep all presentation logic in one place

How to implement Presenter?

There is a great post by Harold Gimnez on how to implement Presenter in rails.

http://robots.thoughtbot.com/post/13641910701/tidy-views-and-beyond-with-decorators

Don't confuse with helper with Presenter

Simple logic goes to helper

Logic that don't relate to object, goes to helper

Logic relate to object, goes to Presenter

Too complex logic can also go to Presenter

Q & A

Thanks You