In this tutorial we will have a look on Draper gem, which helps us decorate our views more like in object oriented approach. Its a great gem and provides us lots of options to decorate single object and collection of objects. We discussed presenter/decorator pattern in my previous post. We looked different aspects of the pattern and discussed the benefits of using this approach. We used rails SimpleDelegator class to create our decorators. Here we will see how can we use Draper for our decorators.
As per the Draper documentation, decorators are the ideal place to:
1. format complex data for presentation
2. common representation of information example: showing full name from first_name and last_name
3. for formatting html elements example: returning link from url.
In our application we have a products listing page. Here we have several products with images and additional details like pricing,manufacturer , variants etc. The page is so complex that it has number of methods in view helper modules. Its hard to manage helpers when there is too much logic and methods. Also helpers can not be used in object oriented way. The methods in helpers seem much like utility method. There is no receiver of the method. Since rails mixes the methods in view the method is globally available. Suppose i have two methods with same name in two modules, they get mixed in view.
For these reasons we can use decorators instead of using view helpers. We have a Product model. With Draper, we create a corresponding ProductDecorator. The decorator wraps the model, and deals with presentational concerns.
After draper is installed run the generator for product: