Class: Cuprum::Collections::Commands::FindOneMatching

Inherits:
Cuprum::Command
  • Object
show all
Defined in:
lib/cuprum/collections/commands/find_one_matching.rb

Overview

Command for finding a unique entity by a query or set of attributes.

Examples:

Finding An Entity By Attributes

command =
  Cuprum::Collections::Commands::FindOneMatching
  .new(collection: books_collection)

# With an attributes Hash that matches one entity.
result = command.call(attributes: { 'title' => 'Gideon the Ninth' })
result.success?
#=> true
result.value
#=> a Book with title 'Gideon the Ninth'

# With an attributes Hash that matches multiple entities.
result = command.call(attributes: { 'author' => 'Tamsyn Muir' })
result.success?
#=> false
result.error
#=> an instance of Cuprum::Collections::NotUnique

# With an attributes Hash that does not match any entities.
result = command.call(
  attributes: {
    'author' => 'Becky Chambers',
    'series' => 'The Locked Tomb'
  }
)
result.success?
#=> false
result.error
#=> an instance of Cuprum::Collections::NotFound

Finding An Entity By Query

command =
  Cuprum::Collections::Commands::FindOneMatching
  .new(collection: collection)

# With a query that matches one entity.
result = command.call do
  {
    'series'       => 'The Lord of the Rings',
    'published_at' => greater_than('1955-01-01')
  }
end
result.success?
#=> true
result.value
#=> a Book matching the query

# With a query that matches multiple entities.
result = command.call do
  {
    'series'       => 'The Lord of the Rings',
    'published_at' => less_than('1955-01-01')
  }
end
result.success?
#=> false
result.error
#=> an instance of Cuprum::Collections::NotUnique

# With an attributes Hash that does not match any entities.
result = command.call do
  {
    'series'       => 'The Lord of the Rings',
    'published_at' => less_than('1954-01-01')
  }
end
result.success?
#=> false
result.error
#=> an instance of Cuprum::Collections::NotFound

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection:) ⇒ FindOneMatching

Returns a new instance of FindOneMatching.

Parameters:

  • collection (#find_matching)

    The collection to query.



83
84
85
86
87
# File 'lib/cuprum/collections/commands/find_one_matching.rb', line 83

def initialize(collection:)
  super()

  @collection = collection
end

Instance Attribute Details

#collection#find_matching (readonly)

Returns the collection to query.

Returns:

  • (#find_matching)

    the collection to query.



90
91
92
# File 'lib/cuprum/collections/commands/find_one_matching.rb', line 90

def collection
  @collection
end