2012-11-08 13:06:24 +00:00
|
|
|
module Draper
|
|
|
|
class DecoratedAssociation
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
def initialize(owner, association, options)
|
|
|
|
options.assert_valid_keys(:with, :scope, :context)
|
2012-11-08 13:06:24 +00:00
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
@owner = owner
|
2012-11-08 13:06:24 +00:00
|
|
|
@association = association
|
2012-12-19 21:45:22 +00:00
|
|
|
|
|
|
|
@decorator_class = options[:with]
|
|
|
|
@scope = options[:scope]
|
|
|
|
@context = options.fetch(:context, owner.context)
|
2012-11-08 13:06:24 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def call
|
2012-12-11 19:49:39 +00:00
|
|
|
return undecorated if undecorated.nil?
|
2012-12-19 21:45:22 +00:00
|
|
|
decorated
|
2012-11-08 13:06:24 +00:00
|
|
|
end
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
def context
|
|
|
|
return @context.call(owner.context) if @context.respond_to?(:call)
|
|
|
|
@context
|
2012-12-13 02:52:12 +00:00
|
|
|
end
|
|
|
|
|
2012-11-08 13:06:24 +00:00
|
|
|
private
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
attr_reader :owner, :association, :decorator_class, :scope
|
|
|
|
|
|
|
|
def source
|
|
|
|
owner.source
|
|
|
|
end
|
|
|
|
|
2012-11-08 13:06:24 +00:00
|
|
|
def undecorated
|
|
|
|
@undecorated ||= begin
|
|
|
|
associated = source.send(association)
|
2012-12-19 21:45:22 +00:00
|
|
|
associated = associated.send(scope) if scope
|
2012-11-08 13:06:24 +00:00
|
|
|
associated
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
def decorated
|
|
|
|
@decorated ||= decorator.call(undecorated, context: context)
|
2012-11-08 13:06:24 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def collection?
|
|
|
|
undecorated.respond_to?(:first)
|
|
|
|
end
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
def decorator
|
|
|
|
return collection_decorator if collection?
|
2012-11-08 13:06:24 +00:00
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
if decorator_class
|
|
|
|
decorator_class.method(:decorate)
|
2012-11-08 13:06:24 +00:00
|
|
|
else
|
2012-12-19 21:45:22 +00:00
|
|
|
->(item, options) { item.decorate(options) }
|
2012-11-08 13:06:24 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
def collection_decorator
|
|
|
|
klass = decorator_class || Draper::CollectionDecorator
|
2012-12-13 02:52:12 +00:00
|
|
|
|
2012-12-19 21:45:22 +00:00
|
|
|
if klass.respond_to?(:decorate_collection)
|
|
|
|
klass.method(:decorate_collection)
|
|
|
|
else
|
|
|
|
klass.method(:decorate)
|
2012-12-13 02:52:12 +00:00
|
|
|
end
|
|
|
|
end
|
2012-12-19 21:45:22 +00:00
|
|
|
|
2012-11-08 13:06:24 +00:00
|
|
|
end
|
|
|
|
end
|