Sha256: 33323fe9fa6b460977d9292528a2f4f98a729d6955e9e0b2e25a4bfbc47851da

Contents?: true

Size: 1.47 KB

Versions: 42

Compression:

Stored size: 1.47 KB

Contents

module ZendeskAPI
  # @private
  module Sideloading
    def self.included(klass)
      klass.send(:attr_reader, :included)
    end

    def set_includes(resource_or_resources, includes, body)
      @included = {}

      includes.each do |side_load|
        unless body.key?(side_load.to_s)
          @client.config.logger.warn "Missing #{side_load} key in response -- cannot side load"
        end
      end

      resources = to_array(resource_or_resources)
      resource_class = resources.first.class

      return if resources.empty?

      body.keys.each do |name|
        @included[name] = body[name]
        _side_load(name, resource_class, resources)
      end
    end

    private

    # Traverses the resource looking for associations
    # then descends into those associations and checks for applicable
    # resources to side load
    def _side_load(name, klass, resources)
      associations = klass.associated_with(name)

      associations.each do |association|
        association.side_load(resources, @included[name])
      end

      resources.each do |resource|
        loaded_associations = resource.loaded_associations
        loaded_associations.each do |association|
          loaded = resource.send(association[:name])
          next unless loaded
          _side_load(name, association[:class], to_array(loaded))
        end
      end
    end

    def to_array(item)
      if item.is_a?(Collection)
        item
      else
        [item].flatten.compact
      end
    end
  end
end

Version data entries

42 entries across 42 versions & 2 rubygems

Version Path
zendesk_api-3.1.1 lib/zendesk_api/sideloading.rb
zendesk_api-3.1.0 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.5 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.4 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.2 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.1 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.0 lib/zendesk_api/sideloading.rb
zendesk_api-3.0.0.rc1 lib/zendesk_api/sideloading.rb
zendesk_api-2.0.1 lib/zendesk_api/sideloading.rb
zendesk_api-2.0.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.38.0.rc2 lib/zendesk_api/sideloading.rb
zendesk_api-1.38.0.rc1 lib/zendesk_api/sideloading.rb
zendesk_api-1.37.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.36.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.35.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.34.0 lib/zendesk_api/sideloading.rb
discourse_zendesk_api-1.0.1 lib/zendesk_api/sideloading.rb
discourse_zendesk_api-1.0.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.33.0 lib/zendesk_api/sideloading.rb
zendesk_api-1.32.0 lib/zendesk_api/sideloading.rb