Draper
Decorators/View-Models for Rails Applications
Install / Use
/learn @drapergem/DraperREADME
Draper: View Models for Rails
Draper adds an object-oriented layer of presentation logic to your Rails application.
Without Draper, this functionality might have been tangled up in procedural helpers or adding bulk to your models. With Draper decorators, you can wrap your models with presentation-related logic to organise - and test - this layer of your app much more effectively.
Why Use a Decorator?
Imagine your application has an Article model. With Draper, you'd create a
corresponding ArticleDecorator. The decorator wraps the model, and deals
only with presentational concerns. In the controller, you decorate the article
before handing it off to the view:
# app/controllers/articles_controller.rb
def show
@article = Article.find(params[:id]).decorate
end
In the view, you can use the decorator in exactly the same way as you would have used the model. But whenever you start needing logic in the view or start thinking about a helper method, you can implement a method on the decorator instead.
Let's look at how you could convert an existing Rails helper to a decorator method. You have this existing helper:
# app/helpers/articles_helper.rb
def publication_status(article)
if article.published?
"Published at #{article.published_at.strftime('%A, %B %e')}"
else
"Unpublished"
end
end
But it makes you a little uncomfortable. publication_status lives in a
nebulous namespace spread across all controllers and view. Down the road, you
might want to display the publication status of a Book. And, of course, your
design calls for a slightly different formatting to the date for a Book.
Now your helper method can either switch based on the input class type (poor
Ruby style), or you break it out into two methods, book_publication_status and
article_publication_status. And keep adding methods for each publication
type...to the global helper namespace. And you'll have to remember all the names. Ick.
Ruby thrives when we use Object-Oriented style. If you didn't know Rails' helpers existed, you'd probably imagine that your view template could feature something like this:
<%= @article.publication_status %>
Without a decorator, you'd have to implement the publication_status method in
the Article model. That method is presentation-centric, and thus does not
belong in a model.
Instead, you implement a decorator:
# app/decorators/article_decorator.rb
class ArticleDecorator < Draper::Decorator
delegate_all
def publication_status
if published?
"Published at #{published_at}"
else
"Unpublished"
end
end
def published_at
object.published_at.strftime("%A, %B %e")
end
end
Within the publication_status method we use the published? method. Where
does that come from? It's a method of the source Article, whose methods have
been made available on the decorator by the delegate_all call above.
You might have heard this sort of decorator called a "presenter", an "exhibit", a "view model", or even just a "view" (in that nomenclature, what Rails calls "views" are actually "templates"). Whatever you call it, it's a great way to replace procedural helpers like the one above with "real" object-oriented programming.
Decorators are the ideal place to:
- format complex data for user display
- define commonly-used representations of an object, like a
namemethod that combinesfirst_nameandlast_nameattributes - mark up attributes with a little semantic HTML, like turning a
urlfield into a hyperlink
Installation
As of version 4.0.0, Draper only officially supports Rails 5.2 / Ruby 2.4 and later. Add Draper to your Gemfile.
gem 'draper'
After that, run bundle install within your app's directory.
If you're upgrading from a 0.x release, the major changes are outlined in the wiki.
Writing Decorators
Decorators inherit from Draper::Decorator, live in your app/decorators
directory, and are named for the model that they decorate:
# app/decorators/article_decorator.rb
class ArticleDecorator < Draper::Decorator
# ...
end
To decorate a model in a namespace e.g. Admin::Catalogue place the decorator under the
directory app/decorators/admin in the same way you would with views and models.
# app/decorators/admin/catalogue_decorator.rb
class Admin::CatalogueDecorator < Draper::Decorator
# ...
end
Generators
To create an ApplicationDecorator that all generated decorators inherit from, run...
rails generate draper:install
When you have Draper installed and generate a controller...
rails generate resource Article
...you'll get a decorator for free!
But if the Article model already exists, you can run...
rails generate decorator Article
...to create the ArticleDecorator.
If you don't want Rails to generate decorator files when generating a new controller,
you can add the following configuration to your config/application.rb file:
config.generators do |g|
g.decorator false
end
Accessing Helpers
Normal Rails helpers are still useful for lots of tasks. Both Rails' provided
helpers and those defined in your app can be accessed within a decorator via the h method:
class ArticleDecorator < Draper::Decorator
def emphatic
h.content_tag(:strong, "Awesome")
end
end
If writing h. frequently is getting you down, you can add...
include Draper::LazyHelpers
...at the top of your decorator class - you'll mix in a bazillion methods and
never have to type h. again.
(Note: the capture method is only available through h or helpers)
Accessing the model
When writing decorator methods you'll usually need to access the wrapped model.
While you may choose to use delegation (covered below)
for convenience, you can always use the object (or its alias model):
class ArticleDecorator < Draper::Decorator
def published_at
object.published_at.strftime("%A, %B %e")
end
end
Decorating Objects
Single Objects
Ok, so you've written a sweet decorator, now you're going to want to put it into
action! A simple option is to call the decorate method on your model:
@article = Article.first.decorate
This infers the decorator from the object being decorated. If you want more
control - say you want to decorate a Widget with a more general
ProductDecorator - then you can instantiate a decorator directly:
@widget = ProductDecorator.new(Widget.first)
# or, equivalently
@widget = ProductDecorator.decorate(Widget.first)
Collections
Decorating Individual Elements
If you have a collection of objects, you can decorate them all in one fell swoop:
@articles = ArticleDecorator.decorate_collection(Article.all)
If your collection is an ActiveRecord query, you can use this:
@articles = Article.popular.decorate
Note: In Rails 3, the .all method returns an array and not a query. Thus you
cannot use the technique of Article.all.decorate in Rails 3. In Rails 4,
.all returns a query so this techique would work fine.
Decorating the Collection Itself
If you want to add methods to your decorated collection (for example, for
pagination), you can subclass Draper::CollectionDecorator:
# app/decorators/articles_decorator.rb
class ArticlesDecorator < Draper::CollectionDecorator
def page_number
42
end
end
# elsewhere...
@articles = ArticlesDecorator.new(Article.all)
# or, equivalently
@articles = ArticlesDecorator.decorate(Article.all)
Draper decorates each item by calling the decorate method. Alternatively, you can
specify a decorator by overriding the collection decorator's decorator_class
method, or by passing the :with option to the constructor.
Using pagination
Some pagination gems add methods to ActiveRecord::Relation. For example,
Kaminari's paginate helper method
requires the collection to implement current_page, total_pages, and
limit_value. To expose these on a collection decorator, you can delegate to
the object:
class PaginatingDecorator < Draper::CollectionDecorator
delegate :current_page, :total_pages, :limit_value, :entry_name, :total_count, :offset_value, :last_page?
end
The delegate method used here is the same as that added by Active
Support,
except that the :to option is not required; it defaults to :object when
omitted.
will_paginate needs the following delegations:
delegate :current_page, :per_page, :offset, :total_entries, :total_pages
If needed, you can then set the collection_decorator_class of your CustomDecorator as follows:
class ArticleDecorator < Draper::Decorator
def self.collection_decorator_class
PaginatingDecorator
end
end
ArticleDecorator.decorate_collection(@articles.paginate)
# => Collection decorated by PaginatingDecorator
# => Members decorated by ArticleDecorator
Decorating Associated Objects
You can automatically decorate associated models when the primary model is
decorated. Assuming an Article model has an associated Author object:
class ArticleDecorator < Draper::Decorator
decorates_association :author
end
When ArticleDecorator decorates an Article, it will also use
AuthorDecorator to decorate the associated Author.
Decorated Finders
You can call `decorates_finde
