Class: Treaty::Inventory::Collection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/treaty/inventory/collection.rb

Overview

Collection wrapper for sets of inventory items.

## Purpose

Provides a unified interface for working with collections of inventory items. Uses Ruby Set internally for uniqueness but exposes Array-like interface.

## Usage

Used internally by:

  • Inventory::Factory (to store inventory items during DSL processing)

## Methods

Delegates common collection methods to internal Set:

  • ‘<<` - Add inventory item

  • ‘empty?` - Check if collection is empty

Custom methods:

  • ‘exists?` - Returns true if collection is not empty

  • ‘evaluate` - Evaluates all inventory items with context

## Example

collection = Collection.new
collection << Inventory.new(name: :posts, source: :load_posts)
collection << Inventory.new(name: :meta, source: -> { { count: 10 } })
collection.size  # => 2
collection.exists?  # => true

Instance Method Summary collapse

Constructor Details

#initialize(collection = Set.new) ⇒ Collection

Creates a new collection instance

Parameters:

  • collection (Set) (defaults to: Set.new)

    Initial collection (default: empty Set)



42
43
44
# File 'lib/treaty/inventory/collection.rb', line 42

def initialize(collection = Set.new)
  @collection = collection
end

Instance Method Details

#evaluate(context) ⇒ Hash{Symbol => Object}

Evaluates all inventory items with the given context

Parameters:

  • context (Object)

    The controller instance to call methods on

Returns:

  • (Hash{Symbol => Object})

    Hash of inventory name => resolved value



64
65
66
67
68
# File 'lib/treaty/inventory/collection.rb', line 64

def evaluate(context)
  @collection.each_with_object({}) do |inventory_item, hash|
    hash[inventory_item.name] = inventory_item.evaluate(context)
  end
end

#exists?Boolean

Checks if collection has any elements

Returns:

  • (Boolean)

    True if collection is not empty



49
50
51
# File 'lib/treaty/inventory/collection.rb', line 49

def exists?
  !empty?
end

#namesArray<Symbol>

Returns array of all inventory item names

Returns:

  • (Array<Symbol>)

    Array of inventory item names



56
57
58
# File 'lib/treaty/inventory/collection.rb', line 56

def names
  @collection.each_with_object([]) { |item, names| names << item.name }
end