Sha256: 9a2495eca38aab8c00f8368cb63d3aea41ca83ee283e925df845a9c297e6864c

Contents?: true

Size: 2 KB

Versions: 2

Compression:

Stored size: 2 KB

Contents

# frozen_string_literal: true

module Trav3
  class ResponseCollection
    extend Forwardable
    def_delegators :@collection, :count, :keys, :values, :has_key?, :key?, :empty?
    def initialize(travis, collection)
      @travis = travis
      @collection = collection
    end

    def [](target)
      result = collection[target]
      return ResponseCollection.new(travis, result) if collection?(result)

      result
    end

    def dig(*target)
      return collection.dig(*target) if target.length != 1

      result = collection.dig(*target)
      return ResponseCollection.new(travis, result) if collection?(result)

      result
    end

    def each(&block)
      return collection.each(&block) if hash?

      collection.each do |item|
        yield ResponseCollection.new(travis, item)
      end
    end

    def fetch(idx)
      result = collection.fetch(idx) { nil }
      return ResponseCollection.new(travis, result) if collection?(result)
      return result if result

      # For error raising behavior
      collection.fetch(idx) unless block_given?

      yield
    end

    def first
      self[0]
    end

    # Follows `@href` link within item.
    # If `#hash?` returns `true` then `#follow` takes no parameters.
    # If `#hash?` returns `false` then `#follow` takes an index parameter
    #   for which item in the Array you wish to follow.
    #
    # @param idx [Integer] (optional parameter) index of array of item to follow `@href` url from
    # @return [Success, RequestError]
    def follow(idx = nil)
      if href? && !idx
        url = collection.fetch('@href')
        return travis.send(:get_path_with_opts, url)
      end

      result = fetch(idx)
      result.follow
    end

    def hash?
      collection.is_a? Hash
    end

    def last
      self[-1]
    end

    private

    def collection?(input)
      [Array, Hash].include? input.class
    end

    def href?
      collection.respond_to?(:key?) and collection.key?('@href')
    end

    attr_reader :travis
    attr_reader :collection
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
trav3-0.4.1 lib/trav3/response/response_collection.rb
trav3-0.4.0 lib/trav3/response/response_collection.rb