Sha256: e23fed719d3ab69ffc62d5493d8da414ec03fdfa3b090ceec20de5adcbc9a158

Contents?: true

Size: 1.76 KB

Versions: 11

Compression:

Stored size: 1.76 KB

Contents

# For "Rails STI" behavior
# CreditCard.all # => [<Visa>, <Mastercard>, etc]
module Graphiti
  class Resource
    module Polymorphism
      def self.prepended(klass)
        klass.extend ClassMethods
      end

      def serializer_for(model)
        if polymorphic_child?
          serializer
        else
          child = self.class.resource_for_model(model)
          child.serializer
        end
      end

      def associate_all(parent, children, association_name, type)
        children.each do |c|
          associate(parent, c, association_name, type)
        end
      end

      def associate(parent, child, association_name, type)
        child_resource = self.class.resource_for_model(parent)
        if child_resource.sideloads[association_name]
          child_resource.new.adapter
            .associate(parent, child, association_name, type)
        end
      end

      module ClassMethods
        def inherited(klass)
          klass.type = nil
          klass.model = klass.infer_model
          klass.endpoint = klass.infer_endpoint
          klass.polymorphic_child = true
          super
        end

        def sideload(name)
          sl = super
          if !polymorphic_child? && sl.nil?
            children.each do |c|
              break if sl = c.sideloads[name]
            end
          end
          sl
        end

        def children
          @children ||= polymorphic.map do |klass|
            klass.is_a?(String) ? klass.safe_constantize : klass
          end
        end

        def resource_for_model(model)
          resource = children.find { |c| model.is_a?(c.model) }
          if resource.nil?
            raise Errors::PolymorphicChildNotFound.new(self, model)
          else
            resource
          end
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
graphiti-1.0.alpha.16 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.15 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.14 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.12 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.11 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.10 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.9 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.8 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.7 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.6 lib/graphiti/resource/polymorphism.rb
graphiti-1.0.alpha.5 lib/graphiti/resource/polymorphism.rb