Rewrite README

Closes #364
Closes #368
Closes #371
[ci skip]
This commit is contained in:
Andrew Haines 2012-12-25 23:33:35 +00:00
parent 9eb9fc909c
commit 52360b656f
5 changed files with 337 additions and 383 deletions

11
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,11 @@
# Contributing to Draper
So you want to help us out... thanks! Here's a quick how-to:
1. [Fork the project](https://help.github.com/articles/fork-a-repo).
2. Create a branch - `git checkout -b adding_magic`
3. Make your changes, and add some tests!
4. Check that the tests pass - `bundle exec rake`
5. Commit your changes - `git commit -am "Added some magic"`
6. Push the branch to Github - `git push origin adding_magic`
7. Send us a [pull request](https://help.github.com/articles/using-pull-requests)!

7
LICENSE Normal file
View File

@ -0,0 +1,7 @@
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

319
README.md Normal file
View File

@ -0,0 +1,319 @@
# Draper: View Models for Rails
[![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.
## Overview
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.
```ruby
# 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. 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:
```ruby
# 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
```
could be better written as:
```ruby
# app/decorators/article_decorator.rb
class ArticleDecorator < Draper::Decorator
def publication_status
if published?
"Published at #{published_at}"
else
"Unpublished"
end
end
def published_at
source.published_at.strftime("%A, %B %e")
end
end
```
Notice that the `published?` method can be called even though `ArticleDecorator` doesn't define it - the decorator delegates 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.
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.
## Installation
Add Draper to your Gemfile:
```ruby
gem 'draper', '~> 1.0'
```
And run `bundle install` within your app's directory.
## Writing decorators
Decorators inherit from `Draper::Decorator`, live in your `app/decorators` directory, and are named for the model that they decorate:
```ruby
# app/decorators/article_decorator.rb
class ArticleDecorator < Draper::Decorator
# ...
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`.
### Accessing helpers
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:
```ruby
class ArticleDecorator < Draper::Decorator
def emphatic
helpers.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).
### 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`):
```ruby
class ArticleDecorator < Draper::Decorator
def published_at
source.published_at.strftime("%A, %B %e")
end
end
```
## Decorating
### 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:
```ruby
@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:
```ruby
@article = ArticleDecorator.new(Article.first)
# or, equivalently
@article = ArticleDecorator.decorate(Article.first)
```
### Collections
If you have a whole bunch of objects, you can decorate them all in one fell swoop:
```ruby
@articles = ArticleDecorator.decorate_collection(Article.all)
# or, for scopes (but not `all`)
@articles = Article.popular.decorate
```
If you want to add methods to your decorated collection (for example, for pagination), you can subclass `Draper::CollectionDecorator`:
```ruby
# 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 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.
### Handy shortcuts
You can automatically decorate associated models:
```ruby
class ArticleDecorator < Draper::Decorator
decorates_association :author
end
```
And, if you want, you can add decorated finder methods:
```ruby
class ArticleDecorator < Draper::Decorator
decorates_finders
end
```
so that you can do:
```ruby
@article = ArticleDecorator.find(params[:id])
```
## Testing
Draper supports RSpec and Minitest::Rails out of the box, and should work with Test::Unit as well.
### RSpec
Your specs should live in `spec/decorators` (if not, 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:
```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.
## Advanced usage
### `ApplicationDecorator`
If you need common methods in your decorators, you can create an `ApplicationDecorator`:
```ruby
# app/decorators/application_decorator.rb
class ApplicationDecorator < Draper::Decorator
# ...
end
```
and inherit from it instead of directly from `Draper::Decorator`.
### Enforcing an interface between controllers and views
If you want to strictly control which methods are called in your views, you can restrict the methods that the decorator delegates to the model. Use `denies` to blacklist methods:
```ruby
class ArticleDecorator < Draper::Decorator
# allow everything except `title` and `author` to be delegated
denies :title, :author
end
```
or, better, use `allows` for a whitelist:
```ruby
class ArticleDecorator < Draper::Decorator
# only allow `title` and `author` to be delegated to the model
allows :title, :author
end
```
You can prevent method delegation altogether using `denies_all`.
### 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
```ruby
Article.first.decorate(context: {role: :admin})
```
The value passed to the `:context` option is then available in the decorator through the `context` method.
If you use `decorates_association`, the context of the parent decorator is passed to the associated decorators. You can override this with the `:context` option:
```ruby
class ArticleDecorator < Draper::Decorator
decorates_association :author, context: {foo: "bar"}
end
```
or, if you simply want to modify the parent's context, use a lambda that takes a hash and returns a new hash:
```ruby
class ArticleDecorator < Draper::Decorator
decorates_association :author,
context: ->(parent_context){ parent_context.merge(foo: "bar") }
end
```
### 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:
```ruby
class ArticleDecorator < Draper::Decorator
decorates_association :author, with: FancyPersonDecorator
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
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
decorates_association :comments, scope: :recent
end
```
### Breaking with convention
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:
```ruby
class MySpecialArticleDecorator < Draper::Decorator
decorates :article
end
```
You don't need to worry about this if you don't want to proxy 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).
### Core Team
* Jeff Casimir (jeff@jumpstartlab.com)
* Steve Klabnik (steve@jumpstartlab.com)
* Vasiliy Ermolovich
* Andrew Haines

View File

@ -1,383 +0,0 @@
# Draper: View Models for Rails
[![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)
## Quick Start
1. Add `gem 'draper'` to your `Gemfile` and `bundle`
2. When you generate a resource with `rails g resource YourModel`, you get a decorator automatically!
3. If `YourModel` already exists, run `rails g decorator YourModel` to create `YourModelDecorator`
4. Edit `app/decorators/[your_model]_decorator.rb` using:
1. `h` to proxy to Rails/application helpers like `h.current_user`
2. the name of your decorated model to access the wrapped object like `article.created_at`
5. Wrap models in your controller with the decorator using:
1. `.decorate` method with a single object,
ex: `ArticleDecorator.decorate(Article.first)`
2. `.new` method with single object
ex: `ArticleDecorator.new(Article.first)`
3. `.decorate_collection` method with a collection,
ex: `ArticleDecorator.decorate_collection(Article.all)`
6. Call decorator methods from your view templates
ex: `<%= @article_decorator.created_at %>`
If you need common methods in your decorators, create an `app/decorators/application_decorator.rb`:
``` ruby
class ApplicationDecorator < Draper::Decorator
# your methods go here
end
```
and make your decorators inherit from it. Newly generated decorators will respect this choice and inherit from `ApplicationDecorator`.
## Goals
This gem makes it easy to apply the decorator pattern to domain models in a Rails application. This pattern gives you three wins:
1. Replace most helpers with an object-oriented approach
2. Filter data at the presentation level
3. Enforce an interface between your controllers and view templates.
### 1. Object Oriented Helpers
Why hate normal helpers? In Ruby/Rails we approach everything from an Object-Oriented perspective, then with helpers we get procedural.The job of a helper is to take in data and output a presentation-ready string. We can do that with a decorator.
A decorator wraps an object with presentation-related accessor methods. For instance, if you had an `Article` object, then the decorator could override `.published_at` to use formatted output like this:
```ruby
class ArticleDecorator < Draper::Decorator
def published_at
date = h.content_tag(:span, article.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = h.content_tag(:span, article.published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
h.content_tag :span, date + time, :class => 'created_at'
end
end
```
### 2. View-Layer Data Filtering
Have you ever written a `to_xml` or `to_json` method in your model? Did it feel weird to put presentation logic in your model?
Or, in the course of formatting this data, did you wish you could access `current_user` down in the model? Maybe for guests your `to_json` is only going to show three attributes, but if the user is an admin they get to see them all.
How would you handle this in the model layer? You'd probably pass the `current_user` or some role/flag down to `to_json`. That should still feel slimy.
When you use a decorator you have the power of a Ruby object but it's a part of the view layer. This is where your `to_json` belongs. You can access your `current_user` helper method using the `h` proxy available in the decorator:
```ruby
class ArticleDecorator < ApplicationDecorator
ADMIN_VISIBLE_ATTRIBUTES = [:title, :body, :author, :status]
PUBLIC_VISIBLE_ATTRIBUTES = [:title, :body]
def to_json
attr_set = h.current_user.admin? ? ADMIN_VISIBLE_ATTRIBUTES : PUBLIC_VISIBLE_ATTRIBUTES
article.to_json(:only => attr_set)
end
end
```
### 3. Enforcing an Interface
Want to strictly control what methods are proxied to the original object? Use `denies` or `allows`.
#### Using `denies`
The `denies` method takes a blacklist approach. For instance:
```ruby
class ArticleDecorator < ApplicationDecorator
denies :title
end
```
Then, to test it:
```irb
> ad = ArticleDecorator.new(Article.find(1))
=> #<ArticleDecorator:0x000001020d7728 @model=#<Article id: 1, title: "Hello, World">>
> ad.title
NoMethodError: undefined method `title' for #<ArticleDecorator:0x000001020d7728>
```
You may also blacklist all methods by using `denies_all`:
```ruby
class ArticleDecorate < ApplicationDecorator
denies_all
end
```
#### Using `allows`
A better approach is to define a whitelist using `allows`:
```ruby
class ArticleDecorator < ApplicationDecorator
allows :title, :description
end
```
```irb
> ad = ArticleDecorator.new(Article.find(1))
=> #<ArticleDecorator:0x000001020d7728 @model=#<Article id: 1, title: "Hello, World">>
> ad.title
=> "Hello, World"
> ad.created_at
NoMethodError: undefined method `created_at' for #<ArticleDecorator:0x000001020d7728>
```
## Up and Running
### Setup
Add the dependency to your `Gemfile`:
```
gem "draper"
```
Then run `bundle` from the project directory.
### Generate the Decorator
To decorate a model named `Article`:
```
rails generate decorator article
```
### Writing Methods
Open the decorator model (ex: `app/decorators/article_decorator.rb`) and add normal instance methods. To access the wrapped source object, use the `model` method:
```ruby
class ArticleDecorator < Draper::Decorator
def author_name
model.author.first_name + " " + model.author.last_name
end
end
```
### Using Existing Helpers
You probably want to make use of Rails helpers and those defined in your application. Use the `helpers` or `h` method proxy:
```ruby
class ArticleDecorator < Draper::Decorator
def published_at
date = h.content_tag(:span, article.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = h.content_tag(:span, article.published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
h.content_tag :span, date + time, :class => 'created_at'
end
end
```
#### Lazy Helpers
Hate seeing that `h.` proxy all over? Willing to mix a bazillion methods into your decorator? Then try lazy helpers:
```ruby
class ArticleDecorator < Draper::Decorator
include Draper::LazyHelpers
def published_at
date = content_tag(:span, article.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = content_tag(:span, article.published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
content_tag :span, date + time, :class => 'created_at'
end
end
```
### In the Controller
When writing your controller actions, you have three options:
* Call `.new` and pass in the object to be wrapped
```ruby
ArticleDecorator.new(Article.find(params[:id]))
```
* Call `.decorate` and pass in an object or collection of objects to be wrapped:
```ruby
ArticleDecorator.decorate(Article.first) # Returns one instance of ArticleDecorator
ArticleDecorator.decorate_collection(Article.all) # Returns CollectionDecorator of ArticleDecorator
```
### In Your Views
Use the new methods in your views like any other model method (ex: `@article.published_at`):
```erb
<h1><%= @article.title %> <%= @article.published_at %></h1>
```
### Integration with RSpec
Using the provided generator, Draper will place specs for your new decorator in `spec/decorators/`.
By default, specs in `spec/decorators` will be tagged as `type => :decorator`. Any spec tagged as `decorator` will make helpers available to the decorator.
If your decorator specs live somewhere else, which they shouldn't, make sure to tag them with `type => :decorator`. If you don't tag them, Draper's helpers won't be available to your decorator while testing.
Note: If you're using Spork, you need to `require 'draper/test/rspec_integration'` in your Spork.prefork block.
## Possible Decoration Methods
Here are some ideas of what you might do in decorator methods:
* Implement output formatting for `to_csv`, `to_json`, or `to_xml`
* Format dates and times using `strftime`
* Implement a commonly used representation of the data object like a `.name` method that combines `first_name` and `last_name` attributes
## Learning Resources
### RailsCast
Ryan Bates has put together an excellent RailsCast on Draper based on the 0.8.0 release: http://railscasts.com/episodes/286-draper
### Example Using a Decorator
For a brief tutorial with sample project, check this out: http://tutorials.jumpstartlab.com/topics/decorators.html
Say I have a publishing system with `Article` resources. My designer decides that whenever we print the `published_at` timestamp, it should be constructed like this:
```html
<span class='published_at'>
<span class='date'>Monday, May 6</span>
<span class='time'>8:52AM</span>
</span>
```
Could we build that using a partial? Yes. A helper? Uh-huh. But the point of the decorator is to encapsulate logic just like we would a method in our models. Here's how to implement it.
First, follow the steps above to add the dependency and update your bundle.
Since we're talking about the `Article` model we'll create an `ArticleDecorator` class. You could do it by hand, but use the provided generator:
```
rails generate decorator Article
```
Now open up the created `app/decorators/article_decorator.rb` and you'll find an `ArticleDecorator` class. Add this method:
```ruby
def published_at
date = h.content_tag(:span, article.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = h.content_tag(:span, article.published_at.strftime("%l:%M%p").delete(" "), :class => 'time')
h.content_tag :span, date + time, :class => 'published_at'
end
```
Then you need to perform the wrapping in your controller. Here's the simplest method:
```ruby
class ArticlesController < ApplicationController
def show
@article = ArticleDecorator.new(Article.find(params[:id]))
end
end
```
Then within your views you can utilize both the normal data methods and your new presentation methods:
```ruby
<%= @article.published_at %>
```
Ta-da! Object-oriented data formatting for your view layer. Below is the complete decorator with extra comments removed:
```ruby
class ArticleDecorator < Draper::Decorator
def published_at
date = h.content_tag(:span, article.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = h.content_tag(:span, article.published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
h.content_tag :span, date + time, :class => 'published_at'
end
end
```
### Example of Decorated Associations
Add a `decorates_association :association_name` to gain access to a decorated version of your target association.
```ruby
class ArticleDecorator < Draper::Decorator
decorates_association :author # belongs_to :author association
end
class AuthorDecorator < Draper::Decorator
def fancy_name
"#{model.title}. #{model.first_name} #{model.middle_name[0]}. #{model.last_name}"
end
end
```
Now when you call the association it will use a decorator.
```ruby
<%= @article.author.fancy_name %>
```
### A note on Rails configuration
Draper loads your application's decorators when Rails start. This may lead to an issue with configuring I18n, whereby the settings you provide in `./config/application.rb` are ignored. This happens when you use the `I18n` constant at the class-level in one of the models that have a decorator, as in the following example:
```ruby
# app/models/user.rb
class User < ActiveRecord::Base
validates :email, presence: { message: I18n.t('invalid_email') }
end
# app/decorators/user_decorator.rb
class UserDecorator < ApplicationDecorator
end
```
Note how the `validates` line is executed when the `User` class is loaded, triggering the initialization of the I18n framework _before_ Rails had a chance to apply its configuration.
Using `I18n` directly in your model definition **is an antipattern**. The preferred solution would be to not override the `message` option in your `validates` macro, but provide the `activerecord.errors.models.attributes.user.email.presence` key in your translation files.
## Extension gems
For automatic decoration, check out [decorates_before_rendering](https://github.com/ohwillie/decorates_before_rendering).
## Contributing
1. Fork it.
2. Create a branch (`git checkout -b my_awesome_branch`)
3. Commit your changes (`git commit -am "Added some magic"`)
4. Push to the branch (`git push origin my_awesome_branch`)
5. Send pull request
## Running tests
If it's the first time you want to run the tests, start by creating the dummy database:
```
$ rake db:migrate
```
You can then run tests by executing `rake`.
## Contributors
Draper was conceived by Jeff Casimir and heavily refined by Steve Klabnik and a great community of open source contributors.
### Core Team
* Jeff Casimir (jeff@jumpstartlab.com)
* Steve Klabnik (steve@jumpstartlab.com)
* Vasiliy Ermolovich
## License
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.