Class: Metior::Collection

Inherits:
HASH_CLASS show all
Defined in:
lib/metior/collections/collection.rb

Overview

Represents a hash retaining insertion order

On Ruby 1.9 this is a subclass of Hash because Ruby 1.9's hashes are already retaining insertion order. For Ruby 1.8 this needs a special parent class OrderedHash provided by the Hashery gem.

Additionally, it provides some shortcuts to make its interface more array-like.

See Also:

  • Hash
  • OrderedHash

Author:

  • Sebastian Staudt

Direct Known Subclasses

ActorCollection, CommitCollection

Instance Method Summary collapse

Constructor Details

#initialize(objects = []) ⇒ Collection

Creates a new collection with the given objects

Parameters:

  • objects (Array<Object>) (defaults to: [])

    The objects that should be initially inserted into the collection



33
34
35
36
37
# File 'lib/metior/collections/collection.rb', line 33

def initialize(objects = [])
  super()

  objects.each { |obj| self << obj }
end

Instance Method Details

#<<(object) ⇒ Collection

Adds an object to this collection

The object should provide a #id method to generate a key for this object.

Parameters:

  • object (Object)

    The object to add to the collection

Returns:

See Also:

  • Array#<<


47
48
49
50
# File 'lib/metior/collections/collection.rb', line 47

def <<(object)
  self[object.id] = object
  self
end

#each {|element| ... } ⇒ Collection

Evaluates the block for each element of the collection

Yields:

  • (element)

    Each of the elements of this collection

Yield Parameters:

  • element (Object)

    The current element of the collection

Returns:



57
58
59
60
# File 'lib/metior/collections/collection.rb', line 57

def each(&block)
  each_value(&block)
  self
end

#lastObject

Returns the element that has been added last to this collection

Returns:

  • (Object)

    The last element of the collection

See Also:

  • Enumerable#last


66
67
68
# File 'lib/metior/collections/collection.rb', line 66

def last
  values.last
end

#merge!(other_collection) ⇒ Collection

Adds all elements of another collection to this one

Parameters:

  • other_collection (Collection)

    The collection to merge into this one

Returns:



76
77
78
79
# File 'lib/metior/collections/collection.rb', line 76

def merge!(other_collection)
  other_collection.each { |obj| self << obj }
  self
end