Sha256: c6ab7d94b4dedf9d5e53774f6ec6c95d569c1644b750ca946c68988127caad9d

Contents?: true

Size: 1.68 KB

Versions: 23

Compression:

Stored size: 1.68 KB

Contents

module Spyke
  module Associations
    class HasMany < Association
      def initialize(*args)
        super
        @options.reverse_merge!(uri: "#{parent_path}/:#{foreign_key}/#{@name}/(:#{primary_key})")
        @params[foreign_key] = parent.id
      end

      def load
        self
      end

      def assign_nested_attributes(incoming)
        incoming = incoming.values if incoming.is_a?(Hash)
        combined_attributes = combine_with_existing(incoming)
        clear_existing!
        combined_attributes.each do |attributes|
          build(attributes)
        end
      end

      private

        def parent_path
          parent.class.model_name.element.pluralize
        end

        def combine_with_existing(incoming)
          return incoming unless primary_keys_present_in_existing?
          combined = embedded_attributes + incoming
          group_by_primary_key(combined).flat_map do |primary_key, hashes|
            if primary_key.present?
              hashes.reduce(:merge)
            else
              hashes
            end
          end
        end

        def group_by_primary_key(array)
          array.group_by { |h| h.with_indifferent_access[primary_key].to_s }
        end

        def primary_keys_present_in_existing?
          embedded_attributes && embedded_attributes.any? { |attr| attr.has_key?(primary_key) }
        end

        def clear_existing!
          update_parent []
        end

        def embedded_attributes
          @embedded_attributes ||= parent.attributes.to_params[name]
        end

        def add_to_parent(record)
          parent.attributes[name] ||= []
          parent.attributes[name] << record
          record
        end
    end
  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
spyke-7.2.2 lib/spyke/associations/has_many.rb
spyke-7.1.1 lib/spyke/associations/has_many.rb
spyke-7.1.0 lib/spyke/associations/has_many.rb
spyke-7.0.0 lib/spyke/associations/has_many.rb
spyke-6.1.3 lib/spyke/associations/has_many.rb
spyke-6.1.2 lib/spyke/associations/has_many.rb
spyke-6.1.1 lib/spyke/associations/has_many.rb
spyke-6.1.0 lib/spyke/associations/has_many.rb
spyke-6.0.0 lib/spyke/associations/has_many.rb
spyke-5.4.3 lib/spyke/associations/has_many.rb
spyke-5.4.2 lib/spyke/associations/has_many.rb
spyke-5.4.1 lib/spyke/associations/has_many.rb
spyke-5.4.0 lib/spyke/associations/has_many.rb
spyke-5.3.4 lib/spyke/associations/has_many.rb
spyke-5.3.3 lib/spyke/associations/has_many.rb
spyke-5.3.2 lib/spyke/associations/has_many.rb
spyke-5.3.1 lib/spyke/associations/has_many.rb
spyke-5.3.0 lib/spyke/associations/has_many.rb
spyke-5.2.0 lib/spyke/associations/has_many.rb
spyke-5.1.0 lib/spyke/associations/has_many.rb