GithubHelp home page GithubHelp logo

drapergem / draper Goto Github PK

View Code? Open in Web Editor NEW
5.2K 71.0 527.0 1.28 MB

Decorators/View-Models for Rails Applications

License: MIT License

Ruby 98.09% HTML 1.86% JavaScript 0.05%
decorators ruby

draper's Introduction

Draper: View Models for Rails

Actions Status Code Climate Test Coverage Inline docs

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 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

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

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.

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_finders in a decorator...

class ArticleDecorator < Draper::Decorator
  decorates_finders
end

...which allows you to then call all the normal ActiveRecord-style finders on your ArticleDecorator and they'll return decorated objects:

@article = ArticleDecorator.find(params[:id])

Decorated Query Methods

By default, Draper will decorate all QueryMethods of ActiveRecord. If you're using another ORM, in order to support it, you can tell Draper to use a custom strategy:

Draper.configure do |config|
  config.default_query_methods_strategy = :mongoid
end

When to Decorate Objects

Decorators are supposed to behave very much like the models they decorate, and for that reason it is very tempting to just decorate your objects at the start of your controller action and then use the decorators throughout. Don't.

Because decorators are designed to be consumed by the view, you should only be accessing them there. Manipulate your models to get things ready, then decorate at the last minute, right before you render the view. This avoids many of the common pitfalls that arise from attempting to modify decorators (in particular, collection decorators) after creating them.

To help you make your decorators read-only, we have the decorates_assigned method in your controller. It adds a helper method that returns the decorated version of an instance variable:

# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
  decorates_assigned :article

  def show
    @article = Article.find(params[:id])
  end
end

The decorates_assigned :article bit is roughly equivalent to

def article
  @decorated_article ||= @article.decorate
end
helper_method :article

This means that you can just replace @article with article in your views and you'll have access to an ArticleDecorator object instead. In your controller you can continue to use the @article instance variable to manipulate the model - for example, @article.comments.build to add a new blank comment for a form.

Configuration

Draper works out the box well, but also provides a hook for you to configure its default functionality. For example, Draper assumes you have a base ApplicationController. If your base controller is named something different (e.g. BaseController), you can tell Draper to use it by adding the following to an initializer:

Draper.configure do |config|
  config.default_controller = BaseController
end

Testing

Draper supports RSpec, MiniTest::Rails, and Test::Unit, and will add the appropriate tests when you generate a decorator.

RSpec

Your specs are expected to live in spec/decorators. If you use a different path, you need to tag them with type: :decorator.

In a controller spec, you might want to check whether your instance variables are being decorated properly. You can use the handy predicate matchers:

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

In your Spork.prefork block of spec_helper.rb, add this:

require 'draper/test/rspec_integration'

Custom Draper Controller ViewContext

If running tests in an engine setting with a controller other than "ApplicationController," set a custom controller in spec_helper.rb

config.before(:each, type: :decorator) do |example|
  Draper::ViewContext.controller = ExampleEngine::CustomRootController.new
end

Isolated Tests

In tests, Draper needs to build a view context to access helper methods. By default, it will create an ApplicationController and then use its view context. If you are speeding up your test suite by testing each component in isolation, you can eliminate this dependency by putting the following in your spec_helper or similar:

Draper::ViewContext.test_strategy :fast

In doing so, your decorators will no longer have access to your application's helpers. If you need to selectively include such helpers, you can pass a block:

Draper::ViewContext.test_strategy :fast do
  include ApplicationHelper
end

Stubbing Route Helper Functions

If you are writing isolated tests for Draper methods that call route helper methods, you can stub them instead of needing to require Rails.

If you are using RSpec, minitest-rails, or the Test::Unit syntax of minitest, you already have access to the Draper helpers in your tests since they inherit from Draper::TestCase. If you are using minitest's spec syntax without minitest-rails, you can explicitly include the Draper helpers:

describe YourDecorator do
  include Draper::ViewHelpers
end

Then you can stub the specific route helper functions you need using your preferred stubbing technique. This examples uses Rspec currently recommended API available in RSpec 3.6+

without_partial_double_verification do
  allow(helpers).to receive(:users_path).and_return('/users')
end

View context leakage

As mentioned before, Draper needs to build a view context to access helper methods. In MiniTest, the view context is cleared during before_setup preventing any view context leakage. In RSpec, the view context is cleared before each decorator, controller, and mailer spec. However, if you use decorators in other types of specs (e.g. job), you may still experience the view context leaking from the previous spec. To solve this, add the following to your spec_helper for each type of spec you are experiencing the leakage:

config.before(:each, type: :type) { Draper::ViewContext.clear! }

Note: The :type above is just a placeholder. Replace :type with the type of spec you are experiencing the leakage from.

Advanced usage

Shared Decorator Methods

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:

# app/decorators/application_decorator.rb
class ApplicationDecorator < Draper::Decorator
# ...
end

Then modify your decorators to inherit from that ApplicationDecorator instead of directly from Draper::Decorator:

class ArticleDecorator < ApplicationDecorator
  # decorator methods
end

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 object. This includes calling super from within the decorator. A call to super from within the decorator will first try to call the method on the parent decorator class. If the method does not exist on the parent decorator class, it will then try to call the method on the decorated object. 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:

class ArticleDecorator < Draper::Decorator
  delegate :title, :body
end

We omit the :to argument here as it defaults to the object being decorated. You could choose to delegate methods to other places like this:

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:

@article.title # Returns the article's `.title`
@article.body  # Returns the article's `.body`
@article.author_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:

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:

class ArticleDecorator < Draper::Decorator
  decorates_association :author, context: {foo: "bar"}
end

or, if you want to modify the parent's context, use a lambda that takes a hash and returns a new hash:

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(s) to perform the decoration. If you want use a specific decorator, you can use the :with option:

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:

class ArticleDecorator < Draper::Decorator
  decorates_association :comments, scope: :recent
end

Proxying Class Methods

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:

class MySpecialArticleDecorator < Draper::Decorator
  decorates :article
end

This is only necessary when proxying class methods.

Once this association between the decorator and the model is set up, you can call SomeModel.decorator_class to access class methods defined in the decorator. If necessary, you can check if your model is decorated with SomeModel.decorator_class?.

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.

Active Job Integration

Active Job allows you to pass ActiveRecord objects to background tasks directly and performs the necessary serialization and deserialization. In order to do this, arguments to a background job must implement Global ID. Decorated objects implement Global ID by delegating to the object they are decorating. This means you can pass decorated objects to background jobs, however, the object won't be decorated when it is deserialized.

Contributors

Draper was conceived by Jeff Casimir and heavily refined by Steve Klabnik and a great community of open source contributors.

Current maintainers

Historical maintainers

draper's People

Contributors

bdotdub avatar blowmage avatar brocktimus avatar brunohkbx avatar cheald avatar codebycliff avatar cookrn avatar haines avatar iblue avatar jcasimir avatar jhsu avatar justinko avatar leshill avatar mange avatar michaelfairley avatar mikezter avatar mjonuschat avatar mschuerig avatar nashby avatar olleolleolle avatar patriciomacadden avatar paulelliott avatar schnittchen avatar seanlinsley avatar steveklabnik avatar stevenbristol avatar stevenharman avatar th1agoalmeida avatar tmaier avatar ubermajestix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

draper's Issues

model.foo doesn't work with twice decorated model

Say I do something like

class ItemDecorator < ApplicationDecorator
  decorates :item

  def pretty_title
    model.title.upcase
  end

end

class ItemSubscriptionDecorator < ItemDecorator
  decorates :item

  def subscription_rates
    1.upto(model.max_rate).to_a
  end

end

Now, if I do

d = ItemSubscriptionDecorator.new(i)
d.pretty_title
d.subscription_rates

then everything works fine. But if I do

c = ItemDecorator.new(i)
d = ItemSubscriptionDecorator.new(c)
d.pretty_title
d.subscription_rates

then the last line will complain about undefined local variable or method 'max_rate' for <123:ItemSubscriptionDecorator>.

I'm guessing it uses respond_to? on whatever is decorated, instead of following the model chain to its root first.

The above might not have been an intended use case, but I think it makes sense to be able to add layers of decoration as you need them. I might only need ItemDecorator in most of the controller/view, but then it renders one partial which needs ItemSubscriptionDecorator.

Might look into this later but only reporting for now.

image_tag helper won't work in decorator

Doing experiments, I've found that the image_tag helper won't work in a decorator. I suspect this is due to something with url_for, but I need to dig into the Rails source.

Can't use url helpers

Dammit, jeff. Keep changing the name and losing my issue. ;)

Can you use url helpers inside of presenters? like account_url(current_user), for example? I haven't tested on HEAD, but you used to not be able to, even though you're including the UrlHelpers module...

Accessing session from Decorator

I've run into some problems when accessing session in a decorator method:

A basic test controller:

class TestController < ...
   def test_page
      session[:test] ||= 0
      session[:test] += 1
      .. 
   end
end

With a decorator:

class TestDecorator < ...
  def test
     h.session[:test]
  end
end

In a view:

Actual session value: <%= session[:test] %>
Decorator value: <%= @decorator.test %>

The first page load displays the same value, but afterwards the value returned by the decorator isn't updated as the session value changes.

request parameter is not updated

Hi

i am trying to refactor some menu-code using simple_navigation into a page-decorator. the page structure is displayed correctly, when visiting a page the first time, but when i visit another page the request parameter is not updated and the therefore the navigation (and highlight) stays the same as before.

Is there a quick fix or do i have to implement the navigation-renderer myself?

thanks

Inconsistencies in README

Here's the final decorator in README:

class ArticleDecorator < Draper::Base
  decorates :article

  def published_at
    date = h.content_tag(:span, published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
    time = h.content_tag(:span, published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
    h.content_tag :span, date + time, :class => 'created_at'
  end
end
  • There's no model. in front of the published_at-methods
  • The class is called created_at; it' published_at in the rest of the README

auto-decorate?

we have a complex domain logic and of course too complicated views. So drapper looks quite nice. But our pages are most of the time mixed resources, a user - has-many x which belongs to y.

In the view we are using helpers from all this objects.

A simple and powerful solution is to auto-decorate any Model via method-missing if we are in a view...

class MyModel  < ActiveRecord::Base

  ...

  def decorator
    @decorator ||= MyModelDecorator.new(self)
  end

  def method_missing(method_name, *args, &block)
    Rails.logger.error("method_name #{method_name}")
    #Rails.logger.error(Draper::ViewContext.current)
    super(method_name, *args, &block) unless Thread.current[:current_view_context] 

    begin
      decorator.send(method_name, *args, &block) 
    rescue NoMethodError
      super
    end
  end
end

but i am not sure if this i too powerful and it also could create way too many objects under the hood.
What do you think?

I'm being forced to use "allows"

Currently, I'm being forced to use "allows". This is because of the way Draper is getting the instance methods:

ruby-1.9.2-p290 :009 > LeadHandler.public_methods.sort.grep(/add_searchable/)
=> []
ruby-1.9.2-p290 :010 > LeadHandler.methods.sort.grep(/add_searchable/)
=> []
ruby-1.9.2-p290 :011 > LeadHandler.instance_methods.sort.grep(/add_searchable/)
=> [:add_searchable_profiles]

I'd love to dig in and find out why instance_methods is including the method but not the others, but sadly I have no time right now :(

nested attributes / nested form and draper followup

I have an issue which is related to #52.

I use in my forms Ryan Bates' nested_form gem. It allows to add and remove new fields with JavaScript.
When I start to use draper, the generated html changes.
Namely the name hash of the field misses one level.

Before draper:

<div class="input string tel optional">
  <label class="tel optional" for="organization_phones_attributes_new_1323093036345_phone_number"> Phone number</label>
  <input class="string tel optional" id="organization_phones_attributes_new_1323093036345_phone_number" name="organization[phones_attributes][new_1323093036345][phone_number]" placeholder="e.g. +49 49 3423232" size="50" type="tel">
  <span class="hint">Has to start with international code, e.g.+49 49 3423232</span>
</div>

Submit results in the following parameters:

  Parameters: {
"utf8"=>"โœ“",
"authenticity_token"=>"qbyOwm7VbFv2MblbKjNyf7HwGGZ97/fHHi6RCI4VDok=",
"organization"=>{
  "name"=>"Example Co. 0",
  "phones_attributes"=>{
    "0"=>{
      "phone_number"=>"49893246240",
      "_destroy"=>"false",
      "id"=>"4eda6313499dda40f700000b"},
    "new_1323093036345"=>{
      "phone_number"=>"+30837748374",
      "_destroy"=>"false"
    }
  }
},
"commit"=>"Update Organization",
"id"=>"4ec580a7499dda4880000006"}

phones_attributes[0] is an existing and already saved record. The HTML for this one is also correct when using draper.
phones_attributes[new_1323093036345] is the new record, created by clicking "Add phone number" and the related JS.

With draper, I get the following HTML.

<div class="input string tel optional">
  <label class="tel optional" for="organization_phones_attributes_phone_number"> Phone number</label>
  <input class="string tel optional" id="organization_phones_attributes_phone_number" name="organization[phones_attributes][phone_number]" placeholder="e.g. +49 49 3423232" size="50" type="tel">
  <span class="hint">Has to start with international code, e.g. +49 49 3423232</span>
</div>

Submit results in the following parameters:

  Parameters: {
"utf8"=>"โœ“",
"authenticity_token"=>"qbyOwm7VbFv2MblbKjNyf7HwGGZ97/fHHi6RCI4VDok=",
"organization"=>{
  "name"=>"Example Co. 0",
  "phones_attributes"=>{
    "0"=>{
      "phone_number"=>"49893246240",
      "_destroy"=>"false",
      "id"=>"4eda6313499dda40f700000b"
    },
  "phone_number"=>"+30837748374",
  "_destroy"=>"false"}
},
"commit"=>"Update Organization",
"id"=>"4ec580a7499dda4880000006"}

Current findings

I think nested_form calls the model attributes at https://github.com/ryanb/nested_form/blob/master/lib/nested_form/builder_mixin.rb in a way how draper does not like it.

Needs to provide "controller" for helper_method helpers

I'm using Devise, which generates its helpers using AbstractController#helper_method. That works like so:

  def helper_method(*meths)
    meths.flatten!
    self._helper_methods += meths

    meths.each do |meth|
      _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
        def #{meth}(*args, &blk)
          controller.send(%(#{meth}), *args, &blk)
        end
      ruby_eval
    end
  end

So the helper ends up wanting to call controller, and that's nil since you don't proxy it. Any ideas how to solve it?

Three doc questions

  1. Your undated blog tutorial says it's not for production use till 1.0. You've bumped the version a few times since then, but still in 0.x; does that still stand?
  2. You don't use the word Presenter anywhere; isn't this particular Decorator pattern the same as Presenters? Even if they're different, it'd be good to explain how they differ, so that (a) we know and (b) people looking for Rails presenters will still find draper through Google.
  3. Can I create a descendant of ApplicationDecorator that doesn't decorate any model classes? I have a few presenter-style classes that don't correspond to models; I'd still like to use the h. helper and other draper sugar.

Problems with Devise?

I noticed that Draper have hard times sometimes when calling the current_user (or whatever youโ€™re using) helper. From time to time, the value is set to nil. And this is something always true when running my cucumber features :/

Any idea?

Use decorator in Rails routes helpers

It's more a question than an issue with draper.

You can use a decorator in rails routes helpers.

event_path(@event) # with @event an EventDecorator

How do you achieve that? I tried to emulate some of the features of draper but can't get that to work.

I have overridden kind_of? in my decorator, since I thought that was the trick, but it doesnt work.
I get Event(#2226668640) expected, got EventPresenter(#2224112480)

Could you explain to me how draper does it?

Thanks :)

UserDecorator.all returns an array of User not UserDecorator. Rails 3.1

While trying to get ActiveScaffold to automatically load and use decorated objects, I tried to use ``UserDecorator.all` which worked, but non-intuitively (to me at least) it returns an array of non-decorated objects, where I expected an array of decorated ones.

My workaround currently consists of

class User < ActiveRecord::Base
  def decorated
    @decorated ||= UserDecorator.new(self)
  end
end

#used like
current_user.decorated.full_name

Which works perfectly well, except for the extra method call everywhere i want to use methods from the decorator.

I don't understand all of the ins and outs of the new Active Record relations that #all is part of, but shouldn't it be possible to add a .decorated type relation that just decorates each result upon return the values? I suspect that would be a better solution than just overriding #all, #find, #first, #last

Using Draper with InheritedResources or ActiveAdmin

I would love to use Draper with a back-end helper like ActiveAdmin... the trouble is that InheritedResources and ActiveAdmin depend a lot on scopes, and thus the ActiveRecord::Relation class.

For example:

>> posts = Post.published   # a scope on the Post model
=> [...some Post instances]
>> posts.class
=> ActiveRecord::Relation
>> posts = PostDecorator.decorate(posts)
=> [...some PostDecorator instances]
>> posts.class
=> Array

After decorating the scoped array of Posts, we lose access to the chainable methods that ActiveAdmin is looking for...

Any thoughts?

Make it easier to write HTML in Ruby

So much boilerplate:

def published_at
  date = h.content_tag(:span, model.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
  time = h.content_tag(:span, model.published_at.strftime("%l:%M%p").delete(" "), :class => 'time')
  h.content_tag :span, date + time, :class => 'published_at'
end

It's much easier to read with a Markaby-inspired syntax:

def published_at
  span :class => :published_at do
    span model.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date'
    span model.published_at.strftime("%l:%M%p").delete(" "), :class => 'time'
  end
end

Or, with CSS-proxies:

def published_at
  span.published_at do
    span.date model.published_at.strftime("%A, %B %e").squeeze(" ")
    span.time model.published_at.strftime("%l:%M%p").delete(" ")
  end
end

decorated.id != model.id

Let's assume we are decorating an Article model with draper-0.8.1:

  article = Article.last
  puts article.id   # ==> 86
  decorated = ArticleDecorator.decorate(article)
  puts decorated.id   # ==> 53599620

Looks like decorated.id returns the decorator's object_id rather than the :id attribute from the database. This is confusing because all other attributes are decorated automatically.

Feature proposal: Decorate collection proxy

I sometimes find it very handy to add decoration methods to the collection object, as well as the individual objects of the collection.

As an example, lets say I have a shop and want to display a list of orders received recently in a table view. I also want to display a summary in the bottom of the table displaying total order value of the visible orders. Typically I would iterate through the order collection and output the individual order as a row, while summing up the amount's into some instance variable.

We can do better - a proposed example for controller and view code:

Controller:

@orders = OrderCollectionDecorator.new(@orders)

View:

%table
  %tbody
    - @orders.each do |order|
      %tr
        %td= order.customer
        %td= order.amount
  %tfoot
    %tr
      %td "Total value of orders:"
      %td= @orders.amount

In this case the last amount, summarizing the total order amount of the orders, is a decorated method on the collection, rather than on the individual models in the collection. The simplicity offered gets even greater when the need arises for more summarizing methods eg. average order value, total number of items in orders etc.

At the moment there's no easy way to implement decoration methods on the collection.

What do you think of this idiom? Is there any way we can achieve it with Draper?

A quick and easy step in the right direction would be to extract the methods of Draper::DecoratedEnumerableProxy into a module, so it as least could be included in the collection decorators. I can certainly do this and open a pull request, but I'd like to get your inputs before hand.

Json generation for collection of decorated objects

If anyone is also having trouble generating json from decorated collections, I suggest you override #as_json on your decorator or ApplicationDecorator to call the respective model #as_json.

class ApplicationDecorator < Draper::Base
  def as_json(options = {})
    model.as_json(options)
  end
end

If you want to provide default options for json generation, I recommend overriding #to_json as well, so you can keep single record and collection json generation consistent.

def to_json(options = {})
  as_json(options).to_json
end

If you're interested in extending json generation to use methods defined inside your decorators(this is helpful for me, at least) you can checkout my lastest commit and extract some ideas from there (angelim@3dfbf3b)

Be careful with association support, though. Draper doesn't support #decorate_association yet and this snippet is using some features that are exclusive to my fork.

I hope this helps someone.

draper doesn't decorate ordered results?

If I have


in my controller, Draper works fine. But

produces a NoMethod error when trying to call a decorator.

I don't really want to call ArticleDecorator.all and then sort the result set in-app (and the pagination won't work properly in that case, anyway). Is there a way to work around this? (Assuming I'm not just doing something monumentally dumb, of course)

"form.label :foo" i18n doesn't work

We've been using form.label :name and relying on Rails i18n to pick up the text from activerecord.attributes.mymodel.name or attributes.name. But when the form object is MymodelDecorator.new(mymodel) instead of just mymodel, this doesn't seem to work.

Just reporting for now โ€“ might dig into it later.

Draper with pagination

I am using will_paginate to paginate the results.
How do we decorate model objects in this case?

In my controller I give something like this

@articles = ArticleDecorator.decorate(Article.paginate(:page => params[:page], :per_page => 5))

But it gives me an error undefined method `total_pages' for #Array:0x9a81e94

Is there any workaround for this?

Decorated attributes inaccessible in to_json

Hello, thanks for outstanding work on draper. I'm having a small issue:

Background:

class ArticleDecorator < ApplicationDecorator
  decorates :article
  PUBLIC_VISIBLE_ATTRIBUTES = [:title]

  def title
    "hello world"
  end

  def to_json
    attr_set = PUBLIC_VISIBLE_ATTRIBUTES
    article.to_json(:only => attr_set)
  end
end

Problem:

a = AricleDecorator.decorate(Article.first)
a.title # => "hello world"
a.to_json # => "{"title": "old title"}"

Am I doing this wrong?

README Refactoring

  1. Add a section about using the decorate helper, both with and without a block.

gem install problem with ruby 1.9.2-p180, rubygems 1.6.2 and greater

Hi,

On installing draper 0.7.0, I get the following error:

$ gem install draper -v=0.7.0
ERROR:  While executing gem ... (NameError)
    uninitialized constant Syck::Syck

After the failed attempt to install, I notice a couple of Syck-specific items in the gemspec as generated from the gem itself. This would seem to be related to this rubygems issue.

As per the title, I'm running ruby 1.9.2-p180, rubygems version 1.6.2. The problem persists with rubygems 1.8.x.

In ree-1.8.7-2001.03 with rubygems 1.5.3, the install completes but the same malformed gemspec is generated, which causes rubygems errors from then on.

If I amend the original gemspec so the rake version specification reads "~> 0.8.7" and rebuild the gem, it seems to work properly - the gem installs fine and the extracted gemspec contains no malformed output. Obviously this isn't ideal, but perhaps it could serve as a workaround until an updated version of rubygems is released containing a fix to the issue I linked?

Anyway, thanks for providing a great-looking gem, I'm looking forward to trying it out...

All the best,
Simon

g.orm :decorator, :invoke_after_finished breaks `rails g migration`

In the README, it's suggested to add the following line to config/application.rb:

g.orm :decorator, :invoke_after_finished => "active_record:model"

However, if you add this, running the following:

rails generate migration add_foo_to_bar

Will invoke active_record:model in such a way that it will create an add_foo_to_bar model, spec, and decorator. This is undesired.

do not double decorate or decorate without a model

a decorator should only decorate a model/collection which exist and also should not double decorate

in base.rb only one line is needed

   def decorate(input, context = {})
       return input if input.is_a?(self.class) || input.blank?  

instead of double decoration it returns the already decorate model and if input is blank it returns nil.
(a better way to check for blank on collection is to use exists? ..(input.respond_to?(:exists?) ? !input.exists? : input.blank? )

but i have a problem to test it, because there is no real ActiveRecord, maybe time to add AR as dependency, at least for development?

Using "presenter" instead of "decorator"

As the project evolves, I increasingly feel that decorator isn't the right terminology. Instead, I'm thinking we should say "presenter."

I had chosen to use "decorator" in part for some dumb personal reasons, but now that people are actually using the project I want to make things more clear to the public.

Thoughts?

Find + Context

If ArticleDecorator.find(1) is valid, then we should support ArticleDecorator.find(1, :admin) to set the context.

Decorators in forms don't handle nested attributes

Didn't have the time to dig into this as much as I'd like, but:

Say I have a form like

form_for(@item) { |f| f.fields_for :subitem { |sf| sf.text_field :name } }

and the item has

accepts_nested_attributes_for :subitem

If @item is a regular model, the nested attributes will be item[subitem_attributes][name] etc.

But if it is a decorator, the nested attributes will be item[subitem][name] etc which breaks.

Use with Inherited Resources

I saw thread #55 (https://github.com/jcasimir/draper/issues/54) and had some success getting Draper and InheritedResources to work that I thought I'd share.

First my admin setup is based on: http://iain.nl/backends-in-rails-3-1#backends-in-rails-3-1.

I first created two Decorators:

class ResourceDecorator < ApplicationDecorator
end
class ProductDecorator < ResourceDecorator
  decorates :product

  def name
    "Hello World"
  end
end

Note the inherited, this lets me super-class common decorator patterns like id or create_at.

My controllers:

class Admin::ResourceController < Admin::ApplicationController
  include ActiveSupport::Inflector

  protected
    def collection
      @cached_collection ||= decorate_resource_or_collection(end_of_association_chain)
    end

    def resource
      @cached_resource ||= decorate_resource_or_collection(super)
    end
  private
    def decorate_resource_or_collection(item_or_items)
      constantize(resource_class.name + "Decorator").decorate(item_or_items)
      rescue NameError
        item_or_items
    end
end
class Admin::ProductController < Admin::ResourceController
end

The obvious short-coming is that the decorator must follow Decorator naming convention. If I need to address that I might down the road, but at least when no decorator is found in falls back to return just the model.

This seems to work well for me now currently. I need to be careful when generating new decorator to edit the parent class from ApplicationDecorator or ResourceDecorator (maybe a future command-line option).

Hope this helps.

Trouble with .classify

I have a Business Model I would like decorated. Inside my app/decorators/business_decorator.rb I have the following line:

  decorates :business

However, while I was working on my Cucumber test, the following error message was displayed:

uninitialized constant Busines (NameError)
[backtrace snipped]
Users/mriffe/.rvm/gems/ruby-1.9.2-p180@wush/gems/draper-0.5.0/lib/draper/base.rb:23:in `decorates'
[rest of the backtrace snipped]

I took a look at the line mentioned in the backtrace and noticed this bit of code:

  self.model_class = input.to_s.classify.constantize

I then loaded up a rails console -s session and proceeded to debug the issue. I soon discovered it was the classify call:

  >> :business.to_s.classify
  => "Busines" 

From the documentation for ActiveSupport::Inflector#classify:

Create a class name from a plural table name like Rails does for table names to models.
Singular names are not handled correctly: "business".classify # => "Busines"

I wondering if camelize wouldn't be a better solution here.

Routes In Decorators

Hey I am running into a weird error with the decorators.
The error/problem is when I have link_to(account_path(model.id)) inside my decorator it works when I render the view. But when I run my rspec decorator test :

### Rspec Test
it "should render link" do
@account = AccountDecorator(account)
@account.tabnavs.should_not be_nil
end

###Decorator
def tabnavs
content_tag(:li, link_to('Summary', account_path(model, :ofc=>"#{model.id}.json"),:remote => true))
end

I get the following error:

AccountDecorator should render link
Failure/Error: @account.tabnavs.should_not be_nil
undefined method `account_path' for #AccountDecorator:0xd9b236

Can you please advise what is needed so the test can understand where to find the account_path

Thanks for a awesome gem
Gerhard

active_support dependency

I'm trying to build a plugin for draper and when requiring draper/base, I get this:

/Users/andrew/code/ruby_apps/draper-cancan/vendor/ruby/1.9.1/gems/draper-0.8.1/lib/draper/base.rb:3:in `require': cannot load such file -- active_support/core_ext/class/attribute (LoadError)
    from /Users/andrew/code/ruby_apps/draper-cancan/vendor/ruby/1.9.1/gems/draper-0.8.1/lib/draper/base.rb:3:in `<class:Base>'
    from /Users/andrew/code/ruby_apps/draper-cancan/vendor/ruby/1.9.1/gems/draper-0.8.1/lib/draper/base.rb:2:in `<module:Draper>'
    from /Users/andrew/code/ruby_apps/draper-cancan/vendor/ruby/1.9.1/gems/draper-0.8.1/lib/draper/base.rb:1:in `<top (required)>'

Does that not mean that draper has an active_support dependency? I know it's only to be used with a rails app and active_support will always be there, but I'm trying to test my addon and it's effects on draper, so there is no need for rails.
Just figured I'd ask...

#decorator method doesn't work properly with cache_classes = false

Due to the way the the #decorator method is added to the decorated class, when cache_classes is false, the decorator class isn't loaded at startup and therefore the #decorator method is never added to the class.

This method seems to be in the very beta stages since there's no documentation around it. It's extremely handy though so I hope someone who knows more than me about Rails load order can find a solution.

Draper > 0.7.4 need rails 3 doesn't works with rails 2

I try use draper on project in rails 2.3.x.

In the dependencies I found activesupport 2.3.10 so I suppose draper works with rails 2.3.x. But only version less than 0.8 works with rails 2.3. The context_wiew using in lib/draper/context_view.rb is appear in Rails 3 and doesn't work with rails 2.3

I propose to update the dependencies to ActiveSupport 3.0 to version after 0.8

Automatically infer certain decorators?

Not an issue with Draper per se but I was hoping this would be a sensible place to ask.

I have a system whereby there could be multiple ways of looking at any particular business object for example. An xml representation, one useful for showing to normal users in HTML, another for showing an admin about flagged items.

Draper of course does not prevent multiple decorators for the same object, and I can see there is work on inferring the correct decorator (https://github.com/jfelchner/draper/commit/404f9d9044c007002a105ac7fae7c89e27a8a4e8).

Is it a sensible use case to develop something like this:

thing.decorate(:xml)
=> XmlThingDecorator
# or
thing.decorate(:flag)
=> FlagThingDecorator
# or
thing.decorate
=> SomeDefaultThingDecorator

If a certain class of decorator does not exist for a class then the decorate method would fall back to a generic decorator:

new_thing.decorate(:flag)
=> FlagDecorator

This of course will have logic that is specific to each app, but is this a useful pattern? Parts of it could be abstracted out and then easily reused.

h#url_for within decorators is broken

Hi Casimir,

I am trying to to build URLs using #url_for from within a decorated model.
My decorator code looks like this:

  class UserDecorator < ApplicationDecorator
    decorates :user

    def admin_url
      h.some_named_route_url(...)
    end
  end

When running the application in development or production the url is built from within the decorator just fine.
This is not the case when I run rspec specs/decorators/user_decorator_spec.rb. Here is what I get :

  julien@dev:project$ rspec spec/decorators/user_decorator_spec.rb

  UserDecorator
    exposes an admin_url (FAILED - 1)

  Failures:

    1) UserDecorator exposes an admin_url
       Failure/Error: puts "S => " + subject.admin_url.inspect
       NoMethodError:
         undefined method `host' for nil:NilClass
       # ./app/decorators/user_decorator.rb:5:in `admin_url'
       # ./spec/decorators/user_decorator_spec.rb:9:in `block (2 levels) in <top (required)>'

  Finished in 0.3617 seconds
  1 example, 1 failure

I read in issue #22 that you worked hard to make the 'view_context' accessible from within a decorator in the testing environment. This is the reason why the generated specs have the following line at the top :

  describe UserDecorator do
    before { ApplicationController.new.set_current_view_context }
  end

I think that the NoMethodError occurs because ApplicationController.new that you inject into the view_context does not embed any request object. So all the routes that need request.host, request.protocol etc... just fail with NoMethodError because h.request is nil.

I found an ugly hack to make url generation work as intended :

  describe UserDecorator do
    before { c = ApplicationController.new
             c.request = ActionDispatch::TestRequest.new
             c.set_current_view_context}
  end

I believe that if my use case works using real requests (in development or production) it should also work when testing using a dummy request. How would you integrate my workaround cleanly into draper ?

Thank you for sharing draper with me.

Sincerely,
Julien

Overriding a model's attribute with a decorator doesn't work within a `form_for`

Consider the following behavior:

> @payment.amount
=> 100.0
> PaymentDecorator.new(@payment).amount
=> $100.00

If I create a form_for around my PaymentDecorator, the amount field is set to 100.0, instead of $100.00.

#to_input_field_tag, in action_view/helpers/form_helper.rb, sets the field value by calling #amount_before_type_cast, which isn't defined in my decorator, and gets called directly on the wrapped object instead. If I define it in my decorator, the output in the form field is as desired ($100.00).

I'm not sure what the consequences of overriding _before_type_cast methods are... it feels a bit wrong! The alternative is to define a formatted_amount method in the decorator, and a formatted_amount=(amount) method in the model, which is basically just self.amount = amount.

I'm happy to submit a pull request if this is a sane idea and is a direction you'd like to go in. I'm also very happy to be pointed in a better direction!

Cheers :)

This gem is not compatible with Ruby 1.8.x

rails g draper:model AlarmConsoleOps
/.rvm/gems/ruby-1.8.7-p330/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239:in `require': .rvm/gems/ruby-1.8.7-p330/gems/draper-0.5.0/lib/draper/all_helpers.rb:33: syntax error, unexpected ':', expecting ')' (SyntaxError)
... args << args.pop.merge(host: ActionMailer::Base.default_ur...
^

It would be cool to make it also work with 1.8... :S

Feature proposal: Decorate associations

Consider we have models User and Post with decorators and a user has_many :posts.
In a controller we expose a user decorator to the view:

 @user_decorator = UserDecorator.find params[:id]

In the view or in the controller it would be nice to access PostDecorators with a concise syntax, like this:

@user_decorator.posts.each do |post_decorator|

In decorator it would be nice to have the following syntax, or something similar:

class UserDecorator < ApplicationDecorator
  decorates :user
  decorates_associations :posts
  ...

Basically the proposal has two parts:

  1. classes Base and DecoratedEnumerableProxy should support lazy decorating of associations ( by analogy with relations/scopes)
  2. define class methods that declare association decorator accessors like this: decorates_associations :posts

With 1st point the problem is here:

base.rb-95-    def self.decorate(input, context = {})
base.rb:96:      input.respond_to?(:each) ? Draper::DecoratedEnumerableProxy.new(input, self, context) : new(input, context)

ActiveRecord::Associations::CollectionProxy does not have each method declared. So the code does not work as desired.

using CanCan within decorator

Thinking this is probably something obvious (but not to me) and wanted to run this use case by you -

Use case: with Ryan Bates' cancan gem and Draper I'd like to be able to link to a resource if the user has read access to it. If not, I'd like to show just the text of the link.

The ugly version in a view

 <% if can? :read, messageboard %>
    <h2><%= link_to messageboard.name, site_messageboards_path(messageboard) %></h2>
  <% else %>
    <h2><%= messageboard.name %></h2>
  <% end %>

What I'd like

<%= messageboard.link_or_text_to %>

But when I extract the if can? ... etc .. out to a decorator I just can't seem to get the can? method to work. I tried h.can? but that didn't help either. Here's what I have

class MessageboardDecorator < Draper::Base
  decorates :messageboard
  include Draper::LazyHelpers

  def link_or_text_to
    @link_or_text = ""
    if can? :read, self
      @link_or_text = link_to name, site_messageboards_path(self)
    else
      @link_or_text = name
    end
    @link_or_text
  end
end

which results in undefined methodcan?' for #MessageboardDecorator:0x0000010799f0b8`

I thought that with lazy helpers loaded the can? method would work. I tried h.can? as well with no luck.

Apologies if this is posted in the wrong place ... if there's a mailing list set up I can bring this up over there.

Thanks, Jeff! Appreciate all the work on this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.