Class: DataMapper::Collection

Class | DataMapper::Collection
In: | lib/dm-core/collection.rb
Parent: | LazyArray

The Collection class represents a list of resources persisted in a repository and identified by a query.

A Collection should act like an Array in every way, except that it will attempt to defer loading until the results from the repository are needed.

A Collection is typically returned by the Model#all method.

### Methods

<< [] []= all at clean? clear collect! concat create create! delete delete_at delete_if destroy destroy! dirty? first first_or_create first_or_new get get! insert inspect last map! model new new pop properties push reject! relationships reload replace repository respond_to? reverse reverse! save save! shift slice slice! splice unshift update update!

### External Aliases

slice | -> | superclass_slice
| Access LazyArray#slice directly Collection#[]= uses this to bypass Collection#slice and access the resources directly so that it can orphan them properly. @api private

### Attributes

query | [R] | Returns the Query the Collection is scoped with @return [Query]
      the Query the Collection is scoped with
@api semipublic

### Public Class methods

new(query, resources = nil)

Initializes a new Collection identified by the query

@param [Query] query

      Scope the results of the Collection

@param [Enumerable] resources (optional)

      List of resources to initialize the Collection with

@return [self]

@api private

### Public Instance methods

<<(resource)

Append one Resource to the Collection and relate it

@param [Resource] resource

      the resource to add to this collection

@return [self]

@api public

[](*args)

Simulates Array#slice and returns a new Collection whose query has a new offset or limit according to the arguments provided.

If you provide a range, the min is used as the offset and the max minues the offset is used as the limit.

@param [Integer, Array(Integer), Range] *args

      the offset, offset and limit, or range indicating first and last position

@return [Resource, Collection, nil]

      The entry which resides at that offset and limit,
      or a new Collection object with the set limits and offset

@return [nil]

      The offset (or starting offset) is out of range

@raise [ArgumentError] "arguments may be 1 or 2 Integers,

      or 1 Range object, was: #{args.inspect}"

@api public

[]=(*args)

Splice a list of Resources at a given offset or range

When nil is provided instead of a Resource or a list of Resources this will remove all of the Resources at the specified position.

@param [Integer, Array(Integer), Range] *args

      The offset, offset and limit, or range indicating first and last position.
      The last argument may be a Resource, a list of Resources or nil.

@return [Resource, Enumerable]

      the Resource or list of Resources that was spliced into the Collection

@return [nil]

      If nil was used to delete the entries

@api public

all(query = nil)

Returns a new Collection optionally scoped by `query`

This returns a new Collection scoped relative to the current Collection.

      cars_from_91 = Cars.all(:year_manufactured => 1991)
      toyotas_91 = cars_from_91.all(:manufacturer => 'Toyota')
      toyotas_91.all? { |car| car.year_manufactured == 1991 }       #=> true
      toyotas_91.all? { |car| car.manufacturer == 'Toyota' }        #=> true

If `query` is a Hash, results will be found by merging `query` with this Collection‘s query. If `query` is a Query, results will be found using `query` as an absolute query.

@param [Hash, Query] query

      optional parameters to scope results with

@return [Collection]

      Collection scoped by +query+

@api public

at(offset)

Lookup a Resource from the Collection by offset

@param [Integer] offset

      offset of the Resource in the Collection

@return [Resource]

      Resource which matches the supplied offset

@return [nil]

      No Resource matches the supplied offset

@api public

clean?()

Checks if all the resources have no changes to save

@return [Boolean]

      true if the resource may not be persisted

@api public

clear()

Removes all Resources from the Collection

This should remove and orphan each Resource from the Collection

@return [self]

@api public

collect!() {|resource_removed(resource)| ...}

Invoke the block for each resource and replace it the return value

@yield [Resource] Each resource in the collection

@return [self]

@api public

concat(resources)

Appends the resources to self

@param [Enumerable] resources

      List of Resources to append to the collection

@return [self]

@api public

create(attributes = {})

Create a Resource in the Collection

@param [Hash(Symbol => Object)] attributes

      attributes to set

@return [Resource]

      the newly created Resource instance

@api public

create!(attributes = {})

Create a Resource in the Collection, bypassing hooks

@param [Hash(Symbol => Object)] attributes

      attributes to set

@return [Resource]

      the newly created Resource instance

@api public

delete(resource)

Remove Resource from the Collection

This should remove an included Resource from the Collection and orphan it from the Collection. If the Resource is not within the Collection, it should return nil.

@param [Resource] resource the Resource to remove from

      the Collection

@return [Resource]

      If +resource+ is within the Collection

@return [nil]

      If +resource+ is not within the Collection

@api public

delete_at(offset)

Remove Resource from the Collection by offset

This should remove the Resource from the Collection at a given offset and orphan it from the Collection. If the offset is out of range return nil.

@param [Integer] offset

      the offset of the Resource to remove from the Collection

@return [Resource]

      If +offset+ is within the Collection

@return [nil]

      If +offset+ is not within the Collection

@api public

delete_if() {|resource| ...}

Deletes every Resource for which block evaluates to true.

@yield [Resource] Each resource in the Collection

@return [self]

@api public

destroy()

Remove every Resource in the Collection from the repository

This performs a deletion of each Resource in the Collection from the repository and clears the Collection.

@return [Boolean]

      true if the resources were successfully destroyed

@api public

destroy!()

Remove all Resources from the repository, bypassing validation

This performs a deletion of each Resource in the Collection from the repository and clears the Collection while skipping validation.

@return [Boolean]

      true if the resources were successfully destroyed

@api public

dirty?()

Checks if any resources have unsaved changes

@return [Boolean]

     true if a resource may be persisted

@api public

first(*args)

Return the first Resource or the first N Resources in the Collection with an optional query

When there are no arguments, return the first Resource in the Collection. When the first argument is an Integer, return a Collection containing the first N Resources. When the last (optional) argument is a Hash scope the results to the query.

@param [Integer] limit (optional)

      limit the returned Collection to a specific number of entries

@param [Hash] query (optional)

      scope the returned Resource or Collection to the supplied query

@return [Resource, Collection]

      The first resource in the entries of this collection,
      or a new collection whose query has been merged

@api public

first_or_create(conditions = {}, attributes = {})

Finds the first Resource by conditions, or creates a new Resource with the attributes if none found

@param [Hash] conditions

      The conditions to be used to search

@param [Hash] attributes

      The attributes to be used to create the resource with if none found

@return [Resource]

      The instance found by +query+, or created with +attributes+ if none found

@api public

first_or_new(conditions = {}, attributes = {})

Finds the first Resource by conditions, or initializes a new Resource with the attributes if none found

@param [Hash] conditions

      The conditions to be used to search

@param [Hash] attributes

      The attributes to be used to initialize the resource with if none found

@return [Resource]

      The instance found by +query+, or created with +attributes+ if none found

@api public

get(*key)

Lookup a Resource in the Collection by key

This looksup a Resource by key, typecasting the key to the proper object if necessary.

      toyotas = Cars.all(:manufacturer => 'Toyota')
      toyo = Cars.first(:manufacturer => 'Toyota')
      toyotas.get(toyo.id) == toyo                  #=> true

@param [Enumerable] *key

      keys which uniquely identify a resource in the Collection

@return [Resource]

      Resource which matches the supplied key

@return [nil]

      No Resource matches the supplied key

@api public

get!(*key)

Lookup a Resource in the Collection by key, raising an exception if not found

This looksup a Resource by key, typecasting the key to the proper object if necessary.

@param [Enumerable] *key

      keys which uniquely identify a resource in the Collection

@return [Resource]

      Resource which matches the supplied key

@return [nil]

      No Resource matches the supplied key

@raise [ObjectNotFoundError] Resource could not be found by key

@api public

insert(offset, *resources)

Inserts the Resources before the Resource at the offset (which may be negative).

@param [Integer] offset

      The offset to insert the Resources before

@param [Enumerable] *resources

      List of Resources to insert

@return [self]

@api public

inspect()

Gets a Human-readable representation of this collection, showing all elements contained in it

@return [String]

      Human-readable representation of this collection, showing all elements

@api public

last(*args)

Return the last Resource or the last N Resources in the Collection with an optional query

When there are no arguments, return the last Resource in the Collection. When the first argument is an Integer, return a Collection containing the last N Resources. When the last (optional) argument is a Hash scope the results to the query.

@param [Integer] limit (optional)

      limit the returned Collection to a specific number of entries

@param [Hash] query (optional)

      scope the returned Resource or Collection to the supplied query

@return [Resource, Collection]

      The last resource in the entries of this collection,
      or a new collection whose query has been merged

@api public

map!()

Alias for collect!

model()

Returns the Model

@return [Model]

      the Model the Collection is associated with

@api semipublic

new(attributes = {})

Initializes a Resource and appends it to the Collection

@param [Hash] attributes

      Attributes with which to initialize the new resource

@return [Resource]

      a new Resource initialized with +attributes+

@api public

pop(*)

Removes and returns the last Resource in the Collection

@return [Resource]

      the last Resource in the Collection

@api public

properties()

Returns the PropertySet representing the fields in the Collection scope

@return [PropertySet]

      The set of properties this Collection's query will retrieve

@api semipublic

push(*resources)

Append one or more Resources to the Collection

This should append one or more Resources to the Collection and relate each to the Collection.

@param [Enumerable] *resources

      List of Resources to append

@return [self]

@api public

reject!() {|resource| ...}

Deletes every Resource for which block evaluates to true

@yield [Resource] Each resource in the Collection

@return [Collection]

      If resources were removed

@return [nil]

      If no resources were removed

@api public

relationships()

Returns the Relationships for the Collection‘s Model

@return [Hash]

      The model's relationships, mapping the name to the
      Associations::Relationship object

@api semipublic

reload(query = nil)

Reloads the Collection from the repository

If `query` is provided, updates this Collection‘s query with its conditions

      cars_from_91 = Cars.all(:year_manufactured => 1991)
      cars_from_91.first.year_manufactured = 2001   # note: not saved
      cars_from_91.reload
      cars_from_91.first.year                       #=> 1991

@param [Query, Hash] query (optional)

      further restrict results with query

@return [self]

@api public

replace(other)

Replace the Resources within the Collection

@param [Enumerable] other

      List of other Resources to replace with

@return [self]

@api public

repository()

Returns the Repository

@return [Repository]

      the Repository this Collection is associated with

@api semipublic

respond_to?(method, include_private = false)

Check to see if collection can respond to the method

@param [Symbol] method

      method to check in the object

@param [Boolean] include_private

      if set to true, collection will check private methods

@return [Boolean]

      true if method can be responded to

@api public

reverse()

Return a copy of the Collection sorted in reverse

@return [Collection]

      Collection equal to +self+ but ordered in reverse

@api public

reverse!()

Return the Collection sorted in reverse

@return [self]

@api public

save()

Save every Resource in the Collection

@return [Boolean]

      true if the resources were successfully saved

@api public

save!()

Save every Resource in the Collection bypassing validation

@return [Boolean]

      true if the resources were successfully saved

@api public

shift(*)

Removes and returns the first Resource in the Collection

@return [Resource]

      the first Resource in the Collection

@api public

slice(*args)

Alias for #[]

slice!(*args)

Deletes and Returns the Resources given by an offset or a Range

@param [Integer, Array(Integer), Range] *args

      the offset, offset and limit, or range indicating first and last position

@return [Resource, Collection]

      The entry which resides at that offset and limit, or
      a new Collection object with the set limits and offset

@return [Resource, Collection, nil]

      The offset is out of range

@api public

splice(*args)

Alias for #[]=

unshift(*resources)

Prepend one or more Resources to the Collection

This should prepend one or more Resources to the Collection and relate each to the Collection.

@param [Enumerable] *resources

      The Resources to prepend

@return [self]

@api public

update(attributes = {})

Update every Resource in the Collection

      Person.all(:age.gte => 21).update(:allow_beer => true)

@param [Hash] attributes

      attributes to update with

@return [Boolean]

      true if the resources were successfully updated

@api public

update!(attributes = {})

Update every Resource in the Collection bypassing validation

      Person.all(:age.gte => 21).update!(:allow_beer => true)

@param [Hash] attributes

      attributes to update

@return [Boolean]

      true if the resources were successfully updated

@api public

[Validate]