Class: Cursed::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cursed/collection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation:, cursor:, adapter: nil) ⇒ Collection

Returns a new instance of Collection.

Parameters:

  • relation (ActiveRecord::Relation or Sequel::Dataset)

    the relation to cursor on

  • cursor (Cursor)

    the value object containing parameters for the cursor

  • adapter (Adapter) (defaults to: nil)

    an object which plays the Adapter role



12
13
14
15
16
# File 'lib/cursed/collection.rb', line 12

def initialize(relation:, cursor:, adapter: nil)
  @relation = relation
  @cursor = cursor
  @adapter = adapter || determine_adapter(relation)
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



7
8
9
# File 'lib/cursed/collection.rb', line 7

def adapter
  @adapter
end

#cursorObject (readonly)

Returns the value of attribute cursor.



7
8
9
# File 'lib/cursed/collection.rb', line 7

def cursor
  @cursor
end

#relationObject (readonly)

Returns the value of attribute relation.



7
8
9
# File 'lib/cursed/collection.rb', line 7

def relation
  @relation
end

Instance Method Details

#each(*args, &block) ⇒ Object

Iterates through each element in the current page



19
20
21
# File 'lib/cursed/collection.rb', line 19

def each(*args, &block)
  collection.each(*args, &block)
end

#invalidate!Object

Invalidates the local cache of the current page - the next call to #each (or any Enumerable method that calls it) will fetch a fresh page.



25
26
27
# File 'lib/cursed/collection.rb', line 25

def invalidate!
  @collection = nil
end

#maximum_idObject

Returns the maximum cursor index in the current page



30
31
32
# File 'lib/cursed/collection.rb', line 30

def maximum_id
  collection.map(&cursor.attribute).max
end

#minimum_idObject

Returns the minimum cursor index in the current page



35
36
37
# File 'lib/cursed/collection.rb', line 35

def minimum_id
  collection.map(&cursor.attribute).min
end

#next_page_paramsHash

Returns a hash of parameters which should be used for generating a next page link.

Returns:

  • (Hash)

    a hash containing any combination of :before, :after, :limit



42
43
44
45
46
47
48
# File 'lib/cursed/collection.rb', line 42

def next_page_params
  if cursor.forward?
    after_maximum_params
  else
    before_minimum_params
  end
end

#prev_page_paramsHash

Returns a hash of parameters which should be used for generating a previous page link.

Returns:

  • (Hash)

    a hash containing any combination of :before, :after, :limit



53
54
55
56
57
58
59
# File 'lib/cursed/collection.rb', line 53

def prev_page_params
  if cursor.forward?
    before_minimum_params
  else
    after_maximum_params
  end
end