Class: Kiss::Iterator

Inherits:
Object show all
Defined in:
lib/kiss/iterator.rb

Overview

Enables ‘loop’ features for certain template loops (while, for…in). Similar to features of Perl’s Template::Iterator by Andy Wardley.

Instance Method Summary collapse

Constructor Details

#initialize(collection = nil) ⇒ Iterator

Creates a new loop iterator.



8
9
10
11
# File 'lib/kiss/iterator.rb', line 8

def initialize(collection = nil)
  @_collection = collection
  @_index = -1
end

Instance Method Details

#countObject

Return current iteration number, indexed from one instead of zero.



14
15
16
# File 'lib/kiss/iterator.rb', line 14

def count
  @_index + 1
end

#first?Boolean Also known as: first

Returns true if this is loop’s first iteration.

Returns:

  • (Boolean)


19
20
21
# File 'lib/kiss/iterator.rb', line 19

def first?
  @_index == 0
end

#incrementObject

Used by template erubis pre-processing voodoo to advance the iterator index. Not intended for any other use.



54
55
56
# File 'lib/kiss/iterator.rb', line 54

def increment
  @_index = @_index + 1
end

#last?Boolean Also known as: last

Returns true if this is the last iteration of a loop over a collection.

Returns:

  • (Boolean)


26
27
28
# File 'lib/kiss/iterator.rb', line 26

def last?
  count == size
end

#maxObject

Returns index of loop’s last iteration.



42
43
44
# File 'lib/kiss/iterator.rb', line 42

def max
  @_collection ? @_collection.size-1 : nil
end

#nextObject

Return next item in loop-iterated collection.



37
38
39
# File 'lib/kiss/iterator.rb', line 37

def next
  @_collection ? @_collection[index+1] : nil
end

#prevObject

Return previous item in loop-iterated collection.



32
33
34
# File 'lib/kiss/iterator.rb', line 32

def prev
  @_collection ? @_collection[index-1] : nil
end

#sizeObject

Returns number of iterations in loop over a collection (size of the iterated collection).



48
49
50
# File 'lib/kiss/iterator.rb', line 48

def size
  @_collection ? @_collection.size : nil
end