Sha256: 0eb86a3b3312a3eb846027928565c6db1a7f0e904a407ef6b76828c6b3773fd4

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

module FulfilApi
  class Resource
    # The {FulfilApi::Resource::Relation} class provides an abstraction for chaining multiple API operations.
    #
    # It allows handling a set of API resources in a uniform way, similar to
    #   ActiveRecord's query interface, enabling the user to build complex queries
    #   in a clean and reusable manner.
    class Relation
      include Enumerable
      include Loadable
      include Naming
      include QueryMethods

      attr_accessor :conditions, :fields, :model_name, :request_limit

      delegate_missing_to :all

      # @param resource_klass [FulfilApi::Resource] The resource data model class.
      def initialize(resource_klass)
        @resource_klass = resource_klass

        @loaded = false
        @resources = []

        reset
      end

      # Loads and returns all resources from Fulfil's API. This method functions as a proxy,
      #   deferring the loading of resources until they are required, thus avoiding unnecessary
      #   HTTP requests.
      #
      # @return [Array<FulfilApi::Resource>] An array of loaded resource objects.
      def all
        load
        @resources
      end

      # The {#each} method allows iteration over the resources. If no block is given,
      #   it returns an Enumerator, enabling lazy evaluation and allowing for chaining
      #   without immediately triggering an API request.
      #
      # @yield [resource] Yields each resource object to the given block.
      # @return [Enumerator, self] Returns an Enumerator if no block is given; otherwise, returns self.
      def each(&block)
        all.each(&block)
      end

      # Resets any of the previously provided query conditions.
      #
      # @return [FulfilApi::Resource::Relation] The relation with cleared query conditions.
      def reset
        @conditions = []
        @fields = %w[id]
        @limit = nil

        self
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
fulfil_api-0.1.4 lib/fulfil_api/resource/relation.rb
fulfil_api-0.1.3 lib/fulfil_api/resource/relation.rb
fulfil_api-0.1.2 lib/fulfil_api/resource/relation.rb
fulfil_api-0.1.1 lib/fulfil_api/resource/relation.rb
fulfil_api-0.1.0 lib/fulfil_api/resource/relation.rb