mirror of
https://github.com/drapergem/draper
synced 2023-03-27 23:21:17 -04:00
Bring over generator structure from rails_decorators
This commit is contained in:
commit
a3804b0662
14 changed files with 400 additions and 0 deletions
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
*.gem
|
||||
.bundle
|
||||
Gemfile.lock
|
||||
pkg/*
|
3
Gemfile
Normal file
3
Gemfile
Normal file
|
@ -0,0 +1,3 @@
|
|||
source :rubygems
|
||||
gem 'actionpack', "~> 3.0.9", :require => 'action_view'
|
||||
gemspec
|
5
Guardfile
Normal file
5
Guardfile
Normal file
|
@ -0,0 +1,5 @@
|
|||
guard 'rspec', :version => 2, :notification => false do
|
||||
watch(%r{^spec/.+_spec\.rb$})
|
||||
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
|
||||
watch('spec/spec_helper.rb') { "spec" }
|
||||
end
|
1
Rakefile
Normal file
1
Rakefile
Normal file
|
@ -0,0 +1 @@
|
|||
require 'bundler/gem_tasks'
|
135
Readme.markdown
Normal file
135
Readme.markdown
Normal file
|
@ -0,0 +1,135 @@
|
|||
Draper
|
||||
================
|
||||
|
||||
This gem makes it easy to apply the decorator pattern to the models in a Rails application.
|
||||
|
||||
## Why use decorators?
|
||||
|
||||
Helpers, as they're commonly used, are a bit odd. In both Ruby and 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 or a data object and output presentation-ready results. We can do that job in an OO fashion with a decorator.
|
||||
|
||||
In general, a decorator wraps an object with presentation-related accessor methods. For instance, if you had an `Article` object, then a decorator might add instance methods like `.formatted_published_at` or `.formatted_title` that output actual HTML.
|
||||
|
||||
## How is it implemented?
|
||||
|
||||
To implement the pattern in Rails we can:
|
||||
|
||||
1. Write a wrapper class with the decoration methods
|
||||
2. Wrap the data object
|
||||
3. Utilize those methods within our view layer
|
||||
|
||||
## How do you utilize this gem in your application?
|
||||
|
||||
Here are the steps to utilizing this gem:
|
||||
|
||||
Add the dependency to your `Gemfile`:
|
||||
|
||||
```
|
||||
gem "draper"
|
||||
```
|
||||
|
||||
Run bundle:
|
||||
|
||||
```
|
||||
bundle
|
||||
```
|
||||
|
||||
Create a decorator for your model (ex: `Article`)
|
||||
|
||||
```
|
||||
rails generate draper:model Article
|
||||
```
|
||||
|
||||
Open the decorator model (ex: `app/decorators/article_decorator.rb`)
|
||||
|
||||
Add your new formatting methods as normal instance or class methods. You have access to the Rails helpers from the following classes:
|
||||
|
||||
```
|
||||
ActionView::Helpers::TagHelper
|
||||
ActionView::Helpers::UrlHelper
|
||||
ActionView::Helpers::TextHelper
|
||||
```
|
||||
|
||||
Use the new methods in your views like any other model method (ex: `@article.formatted_published_at`)
|
||||
|
||||
## 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
|
||||
|
||||
## Example Using a Decorator
|
||||
|
||||
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, update your bundle, then run the `rails generate decorator:setup` to prepare your app.
|
||||
|
||||
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 draper:model Article
|
||||
```
|
||||
|
||||
Now open up the created `app/decorators/article_decorator.rb` and you'll find an `ArticleDecorator` class. Add this method:
|
||||
|
||||
```ruby
|
||||
def formatted_published_at
|
||||
date = content_tag(:span, published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
|
||||
time = content_tag(:span, published_at.strftime("%l:%M%p").delete(" "), :class => 'time')
|
||||
content_tag :span, date + time, :class => 'published_at'
|
||||
end
|
||||
```
|
||||
|
||||
*ASIDE*: Unfortunately, due to the current implementation of `content_tag`, you can't use the style of sending the content is as a block or you'll get an error about `undefined method 'output_buffer='`. Passing in the content as the second argument, as above, works fine.
|
||||
|
||||
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.formatted_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::Base
|
||||
def formatted_published_at
|
||||
date = content_tag(:span, published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
|
||||
time = content_tag(:span, published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
|
||||
content_tag :span, date + time, :class => 'created_at'
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright © 2011 Jeff Casimir
|
||||
|
||||
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.
|
28
draper.gemspec
Normal file
28
draper.gemspec
Normal file
|
@ -0,0 +1,28 @@
|
|||
# -*- encoding: utf-8 -*-
|
||||
$:.push File.expand_path("../lib", __FILE__)
|
||||
require "draper/version"
|
||||
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "draper"
|
||||
s.version = Draper::VERSION
|
||||
s.authors = ["Jeff Casimir"]
|
||||
s.email = ["jeff@casimircreative.com"]
|
||||
s.homepage = "http://github.com/jcasimir/draper"
|
||||
s.summary = "Decorator pattern implmentation for Rails."
|
||||
s.description = "Draper reimagines the role of helpers in the view layer of a Rails application, allowing an object-oriented approach rather than procedural."
|
||||
|
||||
s.rubyforge_project = "draper"
|
||||
|
||||
s.files = `git ls-files`.split("\n")
|
||||
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
|
||||
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
|
||||
s.require_paths = ["lib"]
|
||||
|
||||
s.add_development_dependency "rspec", "~> 2.0.1"
|
||||
s.add_development_dependency "activesupport", "~> 3.0.9"
|
||||
s.add_development_dependency "actionpack", "~> 3.0.9"
|
||||
s.add_development_dependency "ruby-debug19"
|
||||
s.add_development_dependency "guard"
|
||||
s.add_development_dependency "guard-rspec"
|
||||
s.add_development_dependency "rb-fsevent"
|
||||
end
|
2
lib/draper.rb
Normal file
2
lib/draper.rb
Normal file
|
@ -0,0 +1,2 @@
|
|||
require "draper/version"
|
||||
require 'draper/base'
|
46
lib/draper/base.rb
Normal file
46
lib/draper/base.rb
Normal file
|
@ -0,0 +1,46 @@
|
|||
module Draper
|
||||
class Base
|
||||
include ActionView::Helpers::TagHelper
|
||||
include ActionView::Helpers::UrlHelper
|
||||
include ActionView::Helpers::TextHelper
|
||||
|
||||
require 'active_support/core_ext/class/attribute'
|
||||
class_attribute :exclusions, :allowed
|
||||
attr_accessor :source
|
||||
|
||||
DEFAULT_EXCLUSIONS = Object.new.methods
|
||||
self.exclusions = DEFAULT_EXCLUSIONS
|
||||
|
||||
def self.excludes(*input_exclusions)
|
||||
raise ArgumentError, "Specify at least one method (as a symbol) to exclude when using excludes" if input_exclusions.empty?
|
||||
raise ArgumentError, "Use either 'allows' or 'excludes', but not both." if self.allowed?
|
||||
self.exclusions += input_exclusions
|
||||
end
|
||||
|
||||
def self.allows(*input_allows)
|
||||
raise ArgumentError, "Specify at least one method (as a symbol) to allow when using allows" if input_allows.empty?
|
||||
#raise ArgumentError, "Use either 'allows' or 'excludes', but not both." unless (self.exclusions == DEFAULT_EXCLUSIONS)
|
||||
self.allowed = input_allows
|
||||
end
|
||||
|
||||
def initialize(subject)
|
||||
self.source = subject
|
||||
build_methods
|
||||
end
|
||||
|
||||
private
|
||||
def select_methods
|
||||
self.allowed || (source.public_methods - exclusions)
|
||||
end
|
||||
|
||||
def build_methods
|
||||
select_methods.each do |method|
|
||||
(class << self; self; end).class_eval do
|
||||
define_method method do |*args|
|
||||
source.send method, *args
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
3
lib/draper/version.rb
Normal file
3
lib/draper/version.rb
Normal file
|
@ -0,0 +1,3 @@
|
|||
module Draper
|
||||
VERSION = "0.3.0"
|
||||
end
|
7
lib/generators/draper/model/USAGE
Normal file
7
lib/generators/draper/model/USAGE
Normal file
|
@ -0,0 +1,7 @@
|
|||
Description:
|
||||
The draper:model generator creates a decorator model in /app/decorators.
|
||||
|
||||
Examples:
|
||||
rails generate draper:model Article
|
||||
|
||||
file: app/decorators/article_decorator.rb
|
10
lib/generators/draper/model/model_generator.rb
Normal file
10
lib/generators/draper/model/model_generator.rb
Normal file
|
@ -0,0 +1,10 @@
|
|||
module Draper
|
||||
class ModelGenerator < Rails::Generators::NamedBase
|
||||
source_root File.expand_path('../templates', __FILE__)
|
||||
|
||||
def build_model
|
||||
empty_directory "app/decorators"
|
||||
template 'model.rb', "app/decorators/#{singular_name}_decorator.rb"
|
||||
end
|
||||
end
|
||||
end
|
13
lib/generators/draper/model/templates/model.rb
Normal file
13
lib/generators/draper/model/templates/model.rb
Normal file
|
@ -0,0 +1,13 @@
|
|||
class <%= singular_name.camelize %>Decorator < RailsDecorators::Base
|
||||
# Rails helpers like content_tag, link_to, and pluralize are already
|
||||
# available to you. If you need access to other helpers, include them
|
||||
# like this:
|
||||
# include ActionView::Helpers::TextHelper
|
||||
# Or pull in the whole kitchen sink:
|
||||
# include ActionView::Helpers
|
||||
|
||||
# Then define presentation-related instance methods. Ex:
|
||||
# def formatted_created_at
|
||||
# content_tag :span, created_at.strftime("%A")
|
||||
# end
|
||||
end
|
128
spec/base_spec.rb
Normal file
128
spec/base_spec.rb
Normal file
|
@ -0,0 +1,128 @@
|
|||
require 'spec_helper'
|
||||
require 'draper'
|
||||
|
||||
describe Draper::Base do
|
||||
subject{ Draper::Base.new(source) }
|
||||
let(:source){ "Sample String" }
|
||||
|
||||
it "should return the wrapped object when asked for source" do
|
||||
subject.source.should == source
|
||||
end
|
||||
|
||||
it "echos the methods of the wrapped class" do
|
||||
source.methods.each do |method|
|
||||
subject.should respond_to(method)
|
||||
end
|
||||
end
|
||||
|
||||
it "should not copy the .class, .inspect, or other existing methods" do
|
||||
source.class.should_not == subject.class
|
||||
source.inspect.should_not == subject.inspect
|
||||
source.to_s.should_not == subject.to_s
|
||||
end
|
||||
|
||||
describe "a sample usage with excludes" do
|
||||
before(:all) do
|
||||
class DecoratorWithExcludes < Draper::Base
|
||||
excludes :upcase
|
||||
|
||||
def sample_content
|
||||
content_tag :span, "Hello, World!"
|
||||
end
|
||||
|
||||
def sample_link
|
||||
link_to "Hello", "/World"
|
||||
end
|
||||
|
||||
def sample_truncate
|
||||
ActionView::Helpers::TextHelper.truncate("Once upon a time", :length => 7)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
let(:subject_with_excludes){ DecoratorWithExcludes.new(source) }
|
||||
|
||||
it "should not echo methods specified with excludes" do
|
||||
subject_with_excludes.should_not respond_to(:upcase)
|
||||
end
|
||||
|
||||
it "should not clobber other decorators methods" do
|
||||
subject.should respond_to(:upcase)
|
||||
end
|
||||
|
||||
it "should be able to use the content_tag helper" do
|
||||
subject_with_excludes.sample_content.to_s.should == "<span>Hello, World!</span>"
|
||||
end
|
||||
|
||||
it "should be able to use the link_to helper" do
|
||||
subject_with_excludes.sample_link.should == "<a href=\"/World\">Hello</a>"
|
||||
end
|
||||
|
||||
it "should be able to use the pluralize helper" do
|
||||
pending("Figure out odd interaction when the wrapped source object already has the text_helper methods (ie: a String)")
|
||||
subject_with_excludes.sample_truncate.should == "Once..."
|
||||
end
|
||||
end
|
||||
|
||||
describe "a sample usage with allows" do
|
||||
before(:all) do
|
||||
class DecoratorWithAllows < Draper::Base
|
||||
allows :upcase
|
||||
end
|
||||
end
|
||||
|
||||
let(:subject_with_allows){ DecoratorWithAllows.new(source) }
|
||||
|
||||
it "should echo the allowed method" do
|
||||
subject_with_allows.should respond_to(:upcase)
|
||||
end
|
||||
|
||||
it "should echo _only_ the allowed method" do
|
||||
subject_with_allows.should_not respond_to(:downcase)
|
||||
end
|
||||
end
|
||||
|
||||
describe "invalid usages of allows and excludes" do
|
||||
let(:blank_allows){
|
||||
class DecoratorWithInvalidAllows < Draper::Base
|
||||
allows
|
||||
end
|
||||
}
|
||||
|
||||
let(:blank_excludes){
|
||||
class DecoratorWithInvalidExcludes < Draper::Base
|
||||
excludes
|
||||
end
|
||||
}
|
||||
|
||||
let(:using_allows_then_excludes){
|
||||
class DecoratorWithInvalidMixing < Draper::Base
|
||||
allows :upcase
|
||||
excludes :downcase
|
||||
end
|
||||
}
|
||||
|
||||
let(:using_excludes_then_allows){
|
||||
class DecoratorWithInvalidMixing < Draper::Base
|
||||
excludes :downcase
|
||||
allows :upcase
|
||||
end
|
||||
}
|
||||
|
||||
it "should raise an exception for a blank allows" do
|
||||
expect {blank_allows}.should raise_error(ArgumentError)
|
||||
end
|
||||
|
||||
it "should raise an exception for a blank excludes" do
|
||||
expect {blank_excludes}.should raise_error(ArgumentError)
|
||||
end
|
||||
|
||||
it "should raise an exception for mixing allows then excludes" do
|
||||
expect {using_allows_then_excludes}.should raise_error(ArgumentError)
|
||||
end
|
||||
|
||||
it "should raise an exception for calling excludes then allows" do
|
||||
expect {using_excludes_then_allows}.should raise_error(ArgumentError)
|
||||
end
|
||||
end
|
||||
end
|
15
spec/spec_helper.rb
Normal file
15
spec/spec_helper.rb
Normal file
|
@ -0,0 +1,15 @@
|
|||
require 'rubygems'
|
||||
require 'bundler'
|
||||
Bundler.require
|
||||
require 'active_support'
|
||||
require 'action_view'
|
||||
require 'bundler/setup'
|
||||
require 'draper'
|
||||
|
||||
Dir["spec/support/**/*.rb"].each do |file|
|
||||
require "./" + file
|
||||
end
|
||||
|
||||
RSpec.configure do |config|
|
||||
|
||||
end
|
Loading…
Add table
Reference in a new issue