Sha256: eef97bdaf07bed2059ab9895b0ef36e15dbf94ca3a8d5c9cc2cb584d188bbdd5

Contents?: true

Size: 1.95 KB

Versions: 5

Compression:

Stored size: 1.95 KB

Contents

# frozen_string_literal: true

module FulfilApi
  class Resource
    class Relation
      # The {FulfilApi::Resource::Relation::Loadable} extends the relation by
      #   adding methods to load, reload and identify loaded resources from Fulfil's
      #   API endpoints.
      #
      # By default, all HTTP requests to Fulfil are delayed until they're directly
      #   or indirectly requested by the user of the gem. This way, we ensure that
      #   we only request data when we need to.
      module Loadable
        # Loads resources from Fulfil's API based on the current filters, fields, and limits
        #   if they haven't been loaded yet.
        #
        # Requires that {#model_name} is set; raises an exception if it's not.
        #
        # @return [true, false] True if the resources were loaded successfully.
        def load # rubocop:disable Metrics/MethodLength
          return true if loaded?

          if model_name.nil?
            raise FulfilApi::Resource::Relation::ModelNameMissing, "The model name is missing. Use #set to define it."
          end

          response = FulfilApi.client.put(
            "/model/#{model_name}/search_read",
            body: { filters: conditions, fields: fields, limit: request_limit }.compact_blank
          )

          @resources = response.map do |attributes|
            @resource_klass.new(attributes.merge(model_name: model_name))
          end

          @loaded = true
        end

        # Checks whether the resources have been loaded to avoid repeated API calls when
        #   using enumerable methods.
        #
        # @return [true, false] True if the resources are already loaded.
        def loaded?
          @loaded
        end

        # Reloads the resources from Fulfil's API by resetting the {@loaded} flag.
        #
        # @return [true, false] True if the resources were successfully reloaded.
        def reload
          @loaded = false
          load
        end
      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/loadable.rb
fulfil_api-0.1.3 lib/fulfil_api/resource/relation/loadable.rb
fulfil_api-0.1.2 lib/fulfil_api/resource/relation/loadable.rb
fulfil_api-0.1.1 lib/fulfil_api/resource/relation/loadable.rb
fulfil_api-0.1.0 lib/fulfil_api/resource/relation/loadable.rb