drapergem/draper — pull request #543 by aishek (2013-05-22 11:29:48+00:00)
Title: context: nil decorates_association issue

Hi! First of all thanks for a great gem, it really helps to reduce views complexity and develop faster.

I have and issue with draper-1.2.1, rails-3.2.1 app running at ruby-1.9.3-p374.
Having code like (example from pull request):

class Category < ActiveRecord::Base
has_one :item
end

class Item < ActiveRecord::Base
belongs_to :category
end

class CategoryDecorator < Draper::Decorator
decorates_association :item

def item_name
item.name
end
end

class ItemDecorator < Draper::Decorator
def name
"Item#{model.id}"
end
end

class CategoriesController < ApplicationController
def show
@category = CategoryDecorator.new(
Category.find(params[:id]),
context: current_user
)
end

private

# simulate not logged in case
def current_user
nil
end
end

I've got following error's trace output:

ArgumentError - wrong number of arguments (0 for 1):
(gem) draper-1.2.1/lib/draper/decorated_association.rb:14:in `block in initialize'
(gem) draper-1.2.1/lib/draper/factory.rb:87:in `call'
(gem) draper-1.2.1/lib/draper/factory.rb:87:in `update_context'
(gem) draper-1.2.1/lib/draper/factory.rb:46:in `call'
(gem) draper-1.2.1/lib/draper/factory.rb:31:in `decorate'
(gem) draper-1.2.1/lib/draper/decorated_association.rb:31:in `decorate'
(gem) draper-1.2.1/lib/draper/decorated_association.rb:19:in `call'
(gem) draper-1.2.1/lib/draper/decorator.rb:112:in `block in decorates_association'
...

The problem is in [Draper::Factory::Worker#update_context](https://github.com/drapergem/draper/blob/master/lib/draper/factory.rb#L85):

module Draper
class Factory
...
class Worker
...
def update_context(options)
args = options.delete(:context_args)
options[:context] = options[:context].call(*Array.wrap(args)) if options[:context].respond_to?(:call)
end
end
end
end

`Array.wrap(args)` returns `[]` and `options[:context]` contains `->(context){ context }` (see [line 14 decorated_association.rb](https://github.com/drapergem/draper/blob/master/lib/draper/decorated_association.rb#L14)), `(->(context){ context }).call(*[])` raises ArgumentError.

I suggest to fix this by `->(context = nil){ context }`.

Not quite sure, if it is bug or a feature :), because workaround is simple – not to pass nil context to decorators, but I think it'll be convenient to pass current user context like in example above.

Integration spec example and fix in attached pull request.