One pass of revisions

This commit is contained in:
Jeff Casimir 2013-01-14 10:36:50 -07:00
parent bca7fd7330
commit 16de8b912b
1 changed files with 123 additions and 54 deletions

177
README.md
View File

@ -3,12 +3,13 @@
[![TravisCI Build Status](https://secure.travis-ci.org/drapergem/draper.png?branch=master)](http://travis-ci.org/drapergem/draper)
[![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/drapergem/draper)
Draper adds a nicely-separated object-oriented layer of presentation logic to your Rails apps. Previously, this logic might have been tangled up in procedural helpers, or contributing to your fat models' weight problems. Now, you can wrap your models up in decorators to organise - and test - this layer of your app much more effectively.
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.
## Overview
## Why Use a Decorator?
With Draper, your `Article` model has a corresponding `ArticleDecorator`. The decorator wraps the model, and deals only with presentational concerns. In the controller, you simply decorate your article before handing it off to the view.
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:
```ruby
# app/controllers/articles_controller.rb
@ -17,7 +18,9 @@ def show
end
```
In the view, you can use the decorator in exactly the same way as you would have used the model. The difference is, any time you find yourself needing to write a helper, you can implement a method on the decorator instead. For example, this helper:
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 menthod, 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:
```ruby
# app/helpers/articles_helper.rb
@ -30,7 +33,19 @@ def publication_status(article)
end
```
could be better written as:
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 slighly 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 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:
```erb
<%= @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:
```ruby
# app/decorators/article_decorator.rb
@ -51,15 +66,14 @@ class ArticleDecorator < Draper::Decorator
end
```
Notice that the `published?` method can be called even though `ArticleDecorator` doesn't define it - thanks to `delegate_all`, the decorator delegates missing methods to the source model. However, we can override methods like `published_at` to add presentation-specific formatting, in which case we access the underlying model using the `source` method.
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 dates and times using `strftime`,
* define commonly-used representations of an object, like a `name` method that combines `first_name` and `last_name` attributes,
* mark up attributes with a little semantic HTML, like turning a `url` field into a hyperlink.
* format complex data for user display
* define commonly-used representations of an object, like a `name` method that combines `first_name` and `last_name` attributes
* mark up attributes with a little semantic HTML, like turning a `url` field into a hyperlink
## Installation
@ -71,8 +85,7 @@ gem 'draper', '~> 1.0.0'
And run `bundle install` within your app's directory.
## Writing decorators
## Writing Decorators
Decorators inherit from `Draper::Decorator`, live in your `app/decorators` directory, and are named for the model that they decorate:
@ -85,40 +98,56 @@ end
### Generators
When you generate a resource with `rails generate resource Article`, you get a decorator for free! But if the `Article` model already exists, you can run `rails generate decorator Article` to create the `ArticleDecorator`.
When you have Draper installed and generate a resource with...
### Accessing helpers
```
rails generate resource Article
```
...you'll get a decorator for free!
Procedural helpers are still useful for generic tasks like generating HTML, and as such you can access all this goodness (both built-in Rails helpers, and your own) through the `helpers` method:
But if the `Article` model already exists, you can run...
```
rails generate decorator Article
```
...to create the `ArticleDecorator`.
### Accessing Helpers
Normal Rails helpers are still useful for lots tasks. Both Rails' provided helper and those defined in your app can be accessed via the `h` method:
```ruby
class ArticleDecorator < Draper::Decorator
def emphatic
helpers.content_tag(:strong, "Awesome")
h.content_tag(:strong, "Awesome")
end
end
```
To save your typing fingers it's aliased to `h`. If that's still too much effort, just pop `include Draper::LazyHelpers` at the top of your decorator class - you'll mix in a bazillion methods and never have to type `h.` again... [if that's your sort of thing](https://github.com/garybernhardt/base).
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.
### Accessing the model
Decorators will delegate methods to the model where possible, which means in most cases you can replace a model with a decorator and your view won't notice the difference. When you need to get your hands on the underlying model the `source` method is your friend (and its aliases `model` and `to_source`):
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 `source` (or its alias `model`):
```ruby
class ArticleDecorator < Draper::Decorator
delegate_all
def published_at
source.published_at.strftime("%A, %B %e")
end
end
```
## Decorating Objects
## Decorating
### Single objects
### Single Objects
Ok, so you've written a sweet decorator, now you're going to want to put it in action! A simple option is to call the `decorate` method on your model:
@ -140,10 +169,16 @@ If you have a whole bunch of objects, you can decorate them all in one fell swoo
```ruby
@articles = ArticleDecorator.decorate_collection(Article.all)
# or, for scopes (but not `all`)
```
If your collection is an ActiveRecord query, you can use this:
```ruby
@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.
If you want to add methods to your decorated collection (for example, for pagination), you can subclass `Draper::CollectionDecorator`:
```ruby
@ -160,9 +195,9 @@ end
@articles = ArticlesDecorator.decorate(Article.all)
```
Draper guesses the decorator used for each item from the name of the collection decorator (`ArticlesDecorator` becomes `ArticleDecorator`). If that fails, it falls back to using each item's `decorate` method. Alternatively, you can specify a decorator by overriding the collection decorator's `decorator_class` method.
Draper infers the decorator used for each item from the name of the collection decorator (`ArticlesDecorator` implies `ArticleDecorator`). If that fails, it falls back to using each item's `decorate` method. Alternatively, you can specify a decorator by overriding the collection decorator's `decorator_class` method.
Some pagination gems add methods to `ActiveRecord::Relation`. For example, [Kaminari](https://github.com/amatsuda/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 simply delegate to the `source`:
Some pagination gems add methods to `ActiveRecord::Relation`. For example, [Kaminari](https://github.com/amatsuda/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 `source`:
```ruby
class PaginatingDecorator < Draper::CollectionDecorator
@ -172,9 +207,9 @@ end
The `delegate` method used here is the same as that added by [Active Support](http://api.rubyonrails.org/classes/Module.html#method-i-delegate), except that the `:to` option is not required; it defaults to `:source` when omitted.
### Handy shortcuts
### Decorating Associated Objects
You can automatically decorate associated models:
You can automatically decorate associated models when the primary model is decorated. Assuming an `Article` model has an associated `Author` object:
```ruby
class ArticleDecorator < Draper::Decorator
@ -182,7 +217,11 @@ class ArticleDecorator < Draper::Decorator
end
```
And, if you want, you can add decorated finder methods:
When `ArticleDecorator` decorates an `Article`, it will also use `AuthorDecorator` to decorate the associated `Author`.
### Decorated Finders
You can call `decorates_finders` in a decorator...
```ruby
class ArticleDecorator < Draper::Decorator
@ -190,39 +229,46 @@ class ArticleDecorator < Draper::Decorator
end
```
so that you can do:
...which allows you to then call all the normal ActiveRecord-style finders on your `ArticleDecorator` and they'll return decorated objects:
```ruby
@article = ArticleDecorator.find(params[:id])
```
## Testing
Draper supports RSpec, MiniTest::Rails, and Test::Unit, and will add the appropriate tests when you generate a decorator.
### RSpec
Your specs should live in `spec/decorators` (if not, you need to tag them with `type: :decorator`).
Your specs are expected to live in `spec/decorators`. If you use a different path, you need to tag them with `type: :decorator`.
In controller specs, you might want to check whether your instance variables are being decorated properly. You can use the handy predicate matchers:
In a controller spec, you might want to check whether your instance variables are being decorated properly. You can use the handy predicate matchers:
```ruby
assigns(:article).should be_decorated
# or, if you want to be more specific
assigns(:article).should be_decorated_with ArticleDecorator
```
Note that `model.decorate == model`, so your existing specs shouldn't break when you add the decoration.
Spork users should `require 'draper/test/rspec_integration'` in the `Spork.prefork` block.
#### Spork Users
In your `Spork.prefork` block of `spec_helper.rb`, add this:
```ruby
require 'draper/test/rspec_integration'
```
## Advanced usage
### `ApplicationDecorator`
### Shared Decorator Methods
If you need common methods in your decorators, you can create an `ApplicationDecorator`:
You might have several decorators that share similar needs. Since decorators are just Ruby objects, you can use any normal Ruby technique for sharing functionality.
In Rails controllers, common functionality is organized by having all controllers inherit from `ApplicationController`. You can apply this same pattern to your decorators:
```ruby
# app/decorators/application_decorator.rb
@ -231,24 +277,46 @@ class ApplicationDecorator < Draper::Decorator
end
```
and inherit from it instead of directly from `Draper::Decorator`.
### Enforcing an interface between controllers and views
The `delegate_all` call at the top of your decorator means that all missing methods will delegated to the source. If you want to strictly control which methods are called in your views, you can choose to only delegate certain methods.
Then modify your decorators to inherit from that `ApplicationDecorator` instead of directly from `Draper::Decorator`:
```ruby
class ArticleDecorator < Draper::Decorator
delegate :title, :author
class ArticleDecorator < ApplicationDecorator
# decorator methods
end
```
As mentioned above for `CollectionDecorator`, the `delegate` method defaults to using `:source` if the `:to` option is omitted.
### Delegating Methods
When your decorator calls `delegate_all`, any method called on the decorator not defined in the decorator itself will be delegated to the decorated source. This is a very permissive interface.
If you want to strictly control which methods are called within views, you can choose to only delegate certain methods from the decorator to the source model:
```ruby
class ArticleDecorator < Draper::Decorator
delegate :title, :body
end
```
We omit the `:to` argument here as it defaults to the `source` object. You could choose to delegate methods to other places like this:
```ruby
class ArticleDecorator < Draper::Decorator
delegate :title, :body
delegate :name, :title, :to => :author, :prefix => true
end
```
From your view template, assuming `@article` is decorated, you could do any of the following:
```ruby
@article.title # Returns the article's `.title`
@article.name # Returns the article's `author.name`
@article.author_title # Returns the article's `author.title`
```
### Adding context
If you need to pass extra data to your decorators, you can use a `context` hash. Methods that create decorators take it as an option, for example
If you need to pass extra data to your decorators, you can use a `context` hash. Methods that create decorators take it as an option, for example:
```ruby
Article.first.decorate(context: {role: :admin})
@ -264,7 +332,7 @@ class ArticleDecorator < Draper::Decorator
end
```
or, if you simply want to modify the parent's context, use a lambda that takes a hash and returns a new hash:
or, if you want to modify the parent's context, use a lambda that takes a hash and returns a new hash:
```ruby
class ArticleDecorator < Draper::Decorator
@ -273,9 +341,9 @@ class ArticleDecorator < Draper::Decorator
end
```
### Specifying decorators
### Specifying Decorators
When you're using `decorates_association`, Draper uses the `decorate` method on the associated record (or each associated record, in the case of a collection association) to perform the decoration. If you want use a specific decorator, you can use the `:with` option:
When you're using `decorates_association`, Draper uses the `decorate` method on the associated record(s) to perform the decoration. If you want use a specific decorator, you can use the `:with` option:
```ruby
class ArticleDecorator < Draper::Decorator
@ -285,9 +353,9 @@ end
For a collection association, you can specify a `CollectionDecorator` subclass, which is applied to the whole collection, or a singular `Decorator` subclass, which is applied to each item individually.
### Scoping associations
### Scoping Associations
If you want your decorated association to be ordered, limited, or otherwise scoped, you can pass a `:scope` option to `decorates_association`, which will be applied to the collection before decoration:
If you want your decorated association to be ordered, limited, or otherwise scoped, you can pass a `:scope` option to `decorates_association`, which will be applied to the collection *before* decoration:
```ruby
class ArticleDecorator < Draper::Decorator
@ -295,9 +363,11 @@ class ArticleDecorator < Draper::Decorator
end
```
### Breaking with convention
### Proxying Class Methods
If, as well as instance methods, you want to proxy class methods to the model through the decorator (including when using `decorates_finders`), Draper needs to know the model class. By default, it assumes that your decorators are named `SomeModelDecorator`, and then attempts to proxy unknown class methods to `SomeModel`. If your model name can't be inferred from your decorator name in this way, you need to use the `decorates` method:
If you want to proxy class methods to the wrapped model class, including when using `decorates_finders`, Draper needs to know the model class. By default, it assumes that your decorators are named `SomeModelDecorator`, and then attempts to proxy unknown class methods to `SomeModel`.
If your model name can't be inferred from your decorator name in this way, you need to use the `decorates` method:
```ruby
class MySpecialArticleDecorator < Draper::Decorator
@ -305,13 +375,12 @@ class MySpecialArticleDecorator < Draper::Decorator
end
```
You don't need to worry about this if you don't want to proxy class methods.
This is only necessary when proxying class methods.
### Making models decoratable
Models get their `decorate` method from the `Draper::Decoratable` module, which is included in `ActiveRecord::Base` and `Mongoid::Document` by default. If you're using another ORM, or want to decorate plain old Ruby objects, you can include this module manually.
## Contributors
Draper was conceived by Jeff Casimir and heavily refined by Steve Klabnik and a great community of open source [contributors](https://github.com/drapergem/draper/contributors).