2012-12-12 21:52:12 -05:00
|
|
|
require 'draper'
|
|
|
|
|
2012-11-08 08:06:24 -05:00
|
|
|
module Draper
|
|
|
|
class DecoratedAssociation
|
|
|
|
|
2012-12-12 21:52:12 -05:00
|
|
|
attr_reader :base, :association, :options
|
2012-11-08 08:06:24 -05:00
|
|
|
|
2012-12-12 21:52:12 -05:00
|
|
|
def initialize(base, association, options)
|
|
|
|
@base = base
|
2012-11-08 08:06:24 -05:00
|
|
|
@association = association
|
2012-12-12 21:52:12 -05:00
|
|
|
Draper.validate_options(options, :with, :scope, :context)
|
2012-11-08 08:06:24 -05:00
|
|
|
@options = options
|
|
|
|
end
|
|
|
|
|
|
|
|
def call
|
2012-12-11 14:49:39 -05:00
|
|
|
return undecorated if undecorated.nil?
|
2012-11-08 08:06:24 -05:00
|
|
|
decorate
|
|
|
|
end
|
|
|
|
|
2012-12-12 21:52:12 -05:00
|
|
|
def source
|
|
|
|
base.source
|
|
|
|
end
|
|
|
|
|
2012-11-08 08:06:24 -05:00
|
|
|
private
|
|
|
|
|
|
|
|
def undecorated
|
|
|
|
@undecorated ||= begin
|
|
|
|
associated = source.send(association)
|
|
|
|
associated = associated.send(options[:scope]) if options[:scope]
|
|
|
|
associated
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def decorate
|
2012-12-12 21:52:12 -05:00
|
|
|
@decorated ||= decorator_class.send(decorate_method, undecorated, decorator_options)
|
2012-11-08 08:06:24 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def decorate_method
|
|
|
|
if collection? && decorator_class.respond_to?(:decorate_collection)
|
|
|
|
:decorate_collection
|
|
|
|
else
|
|
|
|
:decorate
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def collection?
|
|
|
|
undecorated.respond_to?(:first)
|
|
|
|
end
|
|
|
|
|
|
|
|
def decorator_class
|
|
|
|
return options[:with] if options[:with]
|
|
|
|
|
|
|
|
if collection?
|
|
|
|
options[:with] = :infer
|
|
|
|
Draper::CollectionDecorator
|
|
|
|
else
|
2012-11-08 08:14:01 -05:00
|
|
|
undecorated.decorator_class
|
2012-11-08 08:06:24 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-12-12 21:52:12 -05:00
|
|
|
def decorator_options
|
|
|
|
decorator_class # Ensures options[:with] = :infer for unspecified collections
|
|
|
|
|
|
|
|
dec_options = collection? ? options.slice(:with, :context) : options.slice(:context)
|
|
|
|
dec_options[:context] = base.context unless dec_options.key?(:context)
|
|
|
|
if dec_options[:context].respond_to?(:call)
|
|
|
|
dec_options[:context] = dec_options[:context].call(base.context)
|
|
|
|
end
|
|
|
|
dec_options
|
|
|
|
end
|
2012-11-08 08:06:24 -05:00
|
|
|
end
|
|
|
|
end
|