Class: RnDB::Query

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/rndb/query.rb

Instance Method Summary collapse

Constructor Details

#initialize(table, ids) ⇒ Query

Query records of the given table based on the IDs in the supplied Thicket.



8
9
10
# File 'lib/rndb/query.rb', line 8

def initialize(table, ids)
  @table, @ids = table, ids
end

Instance Method Details

#[](index) ⇒ Object

Retrieve the ID of an index into this query and use it to instantiate a record.



18
19
20
# File 'lib/rndb/query.rb', line 18

def [](index)
  @table[@ids[index]]
end

#countObject

Delegate counting to the Thicket.



13
14
15
# File 'lib/rndb/query.rb', line 13

def count
  @ids.count
end

#eachObject

Delegate iteration to the Thicket, yielding records to the caller.



33
34
35
# File 'lib/rndb/query.rb', line 33

def each
  @ids.each { |id| yield @table[id] }
end

#index(id) ⇒ Object

Retrieve the index of the specified ID.



23
24
25
# File 'lib/rndb/query.rb', line 23

def index(id)
  @ids.index(id)
end

#lastObject

Implemented to be consistent with #first, which we get by magic.



28
29
30
# File 'lib/rndb/query.rb', line 28

def last
  self[-1] unless count.zero?
end

#pluck(*args) ⇒ Object

Return an array or a hash of plucked values, avoiding generation of all attributes.



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rndb/query.rb', line 38

def pluck(*args)
  @ids.map do |id|
    if args.count == 1
      @table.value(id, args.first)
    else
      args.map do |attribute|
        [attribute, @table.value(id, attribute)]
      end.to_h
    end
  end
end

#sample(limit = 1) ⇒ Object

Return a new query that takes a random sampling of IDs from the current query.



51
52
53
54
# File 'lib/rndb/query.rb', line 51

def sample(limit=1)
  _db.prng.srand
  self.class.new(@table, @ids.sample(limit, _db.prng))
end