Sha256: 216005f4dd1a4afe7982a5a31dded9ee705cc05b05c832b9f9e672a01b409e23

Contents?: true

Size: 1.11 KB

Versions: 3

Compression:

Stored size: 1.11 KB

Contents

module Draper
  class DecoratedAssociation

    attr_reader :source, :association, :options

    def initialize(source, association, options)
      @source = source
      @association = association
      @options = options
    end

    def call
      return undecorated if undecorated.nil? || undecorated == []
      decorate
    end

    private

    def undecorated
      @undecorated ||= begin
        associated = source.send(association)
        associated = associated.send(options[:scope]) if options[:scope]
        associated
      end
    end

    def decorate
      @decorated ||= decorator_class.send(decorate_method, undecorated, options)
    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
        undecorated.decorator_class
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
draper-1.0.0.beta3 lib/draper/decorated_association.rb
draper-1.0.0.beta2 lib/draper/decorated_association.rb
draper-1.0.0.beta1 lib/draper/decorated_association.rb