Coder Social home page Coder Social logo

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

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.

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.

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.

README Refactoring

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

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

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.

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

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

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.

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

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

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.

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?

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.

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

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?

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?

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?

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.

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?

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

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

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

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

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

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)

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.

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.

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?

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

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?

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.

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.

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

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.

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

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.

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.

Find + Context

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

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

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

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.