Class: ROM::Memory::Dataset

Inherits:
Object
  • Object
show all
Includes:
ArrayDataset
Defined in:
core/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

Instance Method Details

#delete(tuple) ⇒ Dataset

Delete tuples from a dataset

Parameters:

  • tuple (Hash)

    A new tuple for deletion

Returns:



110
111
112
113
# File 'core/lib/rom/memory/dataset.rb', line 110

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:



97
98
99
100
# File 'core/lib/rom/memory/dataset.rb', line 97

def insert(tuple)
  data << tuple
  self
end

#join(*args) ⇒ Dataset

Join with other datasets

Parameters:

  • args (Array<Dataset>)

    A list of dataset to join with

Returns:



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

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 & t.to_a).any? }
    (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:



80
81
82
83
84
85
86
87
88
# File 'core/lib/rom/memory/dataset.rb', line 80

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:



65
66
67
# File 'core/lib/rom/memory/dataset.rb', line 65

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:



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

def restrict(criteria = nil)
  return find_all { |tuple| yield(tuple) } 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