Sha256: 96a955fd26a71a45f925a77432b9b95a3f9796ab95547475d25e85a52748e39a

Contents?: true

Size: 1.71 KB

Versions: 12

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

require 'active_support'

class DHS::Collection < DHS::Proxy

  module InternalCollection
    extend ActiveSupport::Concern

    # The internal collection class that includes enumerable
    # and insures to return DHS::Items in case of iterating items
    class Collection
      include Enumerable

      attr_accessor :raw

      delegate :length, :size, :first, :last, :sample, :[], :present?, :blank?, :empty?,
               :<<, :push, :insert, to: :raw

      def initialize(raw, parent, record)
        self.raw = raw
        @parent = parent
        @record = record
      end

      def to_ary
        map { |item| item }
      end

      def each(&_block)
        raw.each do |item|
          if item.is_a? Hash
            yield cast_item(item)
          else
            yield item
          end
        end
      end

      def compact
        dup.tap do |collection|
          collection.compact! if collection.raw.present?
        end.as_json # do not return an internal collection!
      end

      def compact!
        self.raw = raw.map do |item|
          if item.is_a?(DHS::Data) && item._request && !item._request.response.success?
            nil
          else
            cast_item(item)
          end
        end.compact
      end

      private

      def cast_item(item)
        data = DHS::Data.new(item, @parent, @record)
        (record_by_href(item) || @record)&.new(data) || data
      end

      def record_by_href(item)
        return if plain_value?(item) || item[:href].blank?

        DHS::Record.for_url(item[:href])
      end

      def plain_value?(item)
        item.is_a?(String) || item.is_a?(Numeric) || item.is_a?(TrueClass) || item.is_a?(FalseClass)
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
dhs-1.6.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.5.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.4.2 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.4.1 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.4.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.3.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.2.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.1.0 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.0.3 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.0.2 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.0.1 lib/dhs/concerns/collection/internal_collection.rb
dhs-1.0.0 lib/dhs/concerns/collection/internal_collection.rb