jcasimir/draper — Issue #99: Use with Inherited Resources
Author: jonlhouse
Created: 2011-12-16 22:18:30+00:00
State: open

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:

```ruby
class ResourceDecorator < ApplicationDecorator
end
```

```ruby
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:

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

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