Class: ROM::Relation::Loaded

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
core/lib/rom/relation/loaded.rb

Overview

Materializes a relation and exposes interface to access the data.

This relation type is returned when a lazy relation is called

Instance Method Summary collapse

Instance Method Details

#each {|Hash| ... } ⇒ Object

Yield relation tuples

Yields:

  • (Hash)


48
49
50
51
52
# File 'core/lib/rom/relation/loaded.rb', line 48

def each
  return to_enum unless block_given?

  collection.each { |tuple| yield(tuple) }
end

#empty?TrueClass, FalseClass

Return if loaded relation is empty

Returns:

  • (TrueClass, FalseClass)


124
125
126
# File 'core/lib/rom/relation/loaded.rb', line 124

def empty?
  collection.empty?
end

#new(collection) ⇒ Object

Return a loaded relation with a new collection



131
132
133
# File 'core/lib/rom/relation/loaded.rb', line 131

def new(collection)
  self.class.new(source, collection)
end

#oneObject

Returns a single tuple from the relation if there is one.

Raises:



60
61
62
63
64
65
66
67
68
69
# File 'core/lib/rom/relation/loaded.rb', line 60

def one
  if collection.count > 1
    raise(
      TupleCountMismatchError,
      'The relation consists of more than one tuple'
    )
  else
    collection.first
  end
end

#one!Object

Like [one], but additionally raises an error if the relation is empty.

Raises:



77
78
79
80
81
82
# File 'core/lib/rom/relation/loaded.rb', line 77

def one!
  one || raise(
    TupleCountMismatchError,
    'The relation does not contain any tuples'
  )
end

#pluck(key) ⇒ Array

Return a list of values under provided key

Examples:

all_users = rom.relations[:users].call
all_users.pluck(:name)
# ["Jane", "Joe"]

Parameters:

  • key (Symbol)

    The key name

Returns:

  • (Array)

Raises:

  • KeyError when provided key doesn't exist in any of the tuples



98
99
100
# File 'core/lib/rom/relation/loaded.rb', line 98

def pluck(key)
  map { |tuple| tuple.fetch(key) }
end

#primary_keysArray

Pluck primary key values

This method may not work with adapters that don't provide relations that have primary key configured

Examples:

users = rom.relations[:users].call
users.primary_keys
# [1, 2, 3]

Returns:

  • (Array)


115
116
117
# File 'core/lib/rom/relation/loaded.rb', line 115

def primary_keys
  pluck(source.primary_key)
end