Class: ROM::Memory::Dataset

Inherits:
Object
  • Object
show all
Includes:
ArrayDataset
Defined in:
lib/rom/memory/dataset.rb

Overview

In-memory dataset

This class can be used as a base class for other adapters.

Instance Method Summary collapse

Methods included from ArrayDataset

included

Methods included from DataProxy::ClassMethods

#forward, #row_proc

Methods included from EnumerableDataset

included

Instance Method Details

#delete(tuple) ⇒ Dataset

Delete tuples from a dataset

Parameters:

  • tuple (Hash)

    A new tuple for deletion

Returns:



112
113
114
115
# File 'lib/rom/memory/dataset.rb', line 112

def delete(tuple)
  data.delete(tuple)
  self
end

#insert(tuple) ⇒ Dataset Also known as: <<

Insert tuple into a dataset

Parameters:

  • tuple (Hash)

    A new tuple for insertion

Returns:



99
100
101
102
# File 'lib/rom/memory/dataset.rb', line 99

def insert(tuple)
  data << tuple
  self
end

#join(*args) ⇒ Dataset

Join with other datasets

rubocop:disable Metrics/AbcSize

Parameters:

  • args (Array<Dataset>)

    A list of dataset to join with

Returns:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rom/memory/dataset.rb', line 23

def join(*args)
  left, right = args.size > 1 ? args : [self, args.first]

  join_map = left.each_with_object({}) { |tuple, h|
    others = right.to_a.find_all { |t| tuple.to_a.intersect?(t.to_a) }
    (h[tuple] ||= []).concat(others)
  }

  tuples = left.flat_map { |tuple|
    join_map[tuple].map { |other| tuple.merge(other) }
  }

  self.class.new(tuples, **options)
end

#order(*fields) ⇒ Dataset

Sort a dataset

Parameters:

  • fields (Array<Symbol>)

    Names of fields to order tuples by

  • [Boolean] (Hash)

    a customizable set of options

Returns:



82
83
84
85
86
87
88
89
90
# File 'lib/rom/memory/dataset.rb', line 82

def order(*fields)
  nils_first = fields.pop[:nils_first] if fields.last.is_a?(Hash)

  sort do |a, b|
    fields # finds the first difference between selected fields of tuples
      .map { |n| __compare__ a[n], b[n], nils_first }
      .detect(-> { 0 }) { |r| r != 0 }
  end
end

#project(*names) ⇒ Dataset

Project a dataset

Parameters:

  • names (Array<Symbol>)

    A list of attribute names

Returns:



67
68
69
# File 'lib/rom/memory/dataset.rb', line 67

def project(*names)
  map { |tuple| tuple.select { |key| names.include?(key) } }
end

#restrict(criteria = nil) ⇒ Dataset

Restrict a dataset

Parameters:

  • criteria (Hash) (defaults to: nil)

    A hash with conditions

Returns:



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rom/memory/dataset.rb', line 46

def restrict(criteria = nil, &)
  return find_all(&) unless criteria

  find_all do |tuple|
    criteria.all? do |k, v|
      case v
      when ::Array then v.include?(tuple[k])
      when ::Regexp then tuple[k].match(v)
      else tuple[k].eql?(v)
      end
    end
  end
end