Module: Progressor::Iteration
- Defined in:
- lib/progressor/iteration.rb
Class Method Summary collapse
-
.each(collection, **options, &block) ⇒ Object
Iterates using ‘.iterate` and the `#each` method.
-
.find_each(collection, **options, &block) ⇒ Object
Iterates using ‘.iterate` and the `#find_each` method.
-
.iterate(method, collection, format: :to_s, **options, &block) ⇒ Object
Iterate the given collection, assuming it responds to:.
Class Method Details
permalink .each(collection, **options, &block) ⇒ Object
Iterates using ‘.iterate` and the `#each` method
51 52 53 |
# File 'lib/progressor/iteration.rb', line 51 def self.each(collection, **, &block) iterate(:each, collection, **, &block) end |
permalink .find_each(collection, **options, &block) ⇒ Object
Iterates using ‘.iterate` and the `#find_each` method
45 46 47 |
# File 'lib/progressor/iteration.rb', line 45 def self.find_each(collection, **, &block) iterate(:find_each, collection, **, &block) end |
permalink .iterate(method, collection, format: :to_s, **options, &block) ⇒ Object
Iterate the given collection, assuming it responds to:
-
The given ‘method` with a block that yields a single item
-
optionally, ‘count` that returns the number of results
It yields two items – the item from the collection and a numeric index. It prints the progress automatically for each loop.
This is meant to be used as a convenience method for ActiveRecord collections with ‘find_each` or `each`, but it could really be used for anything that works with this interface.
Inputs:
-
method: the method name to invoke on ‘collection`
-
collection: the iterable object
-
format: the method to use for printing each individual record. Defaults to ‘:to_s`
-
options: passed along to ‘Progressor::new`
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/progressor/iteration.rb', line 21 def self.iterate(method, collection, format: :to_s, **, &block) if !collection.respond_to?(method) raise Progressor::Error.new("Given collection doesn't respond to ##{method}") end if collection.respond_to?(:count) progressor = Progressor.new(total_count: collection.count, **) else progressor = Progressor.new(**) end index = 0 collection.public_send(method) do |item| progressor.run do |progress| Kernel.puts "[#{progress}] Working on #{item.public_send(format)}" block.call(item, index) index += 1 end end end |