Skip to content

Commit

Permalink
Add while enumerator
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloocana committed Jan 3, 2024
1 parent 92712b9 commit e055d2d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/job-iteration/enumerator_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,32 @@ def build_nested_enumerator(enums, cursor:)
NestedEnumerator.new(enums, cursor: cursor).each
end

# Builds Enumerator for while loop iteration.
#
# @yield Condition to be evaluated before each iteration, the iteration is allowed if a true value is returned.
#
# @example
# def build_enumerator(params)
# enumerator_builder.while query_model_xyz(params).exists?
# end
#
# def each_iteration(count, params)
# query_model_xyz(params).limit(1000).delete_all
# end
#
# def query_model_xyz(params)
# Xyz.where(owner_id: params[:owner_id])
# end
#
def build_while_enumerator(&condition)
count = 0
enum = Enumerator.new do |yielder|
yielder << count += 1 while condition.call
end

wrap(self, enum)
end

alias_method :once, :build_once_enumerator
alias_method :times, :build_times_enumerator
alias_method :array, :build_array_enumerator
Expand All @@ -190,6 +216,7 @@ def build_nested_enumerator(enums, cursor:)
alias_method :throttle, :build_throttle_enumerator
alias_method :csv, :build_csv_enumerator
alias_method :nested, :build_nested_enumerator
alias_method :while, :build_while_enumerator

private

Expand Down
7 changes: 7 additions & 0 deletions test/unit/enumerator_builder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ class EnumeratorBuilderTest < ActiveSupport::TestCase
)
end

test_builder_method(:build_while_enumerator) do
count = 0
enumerator_builder(wraps: 3).build_while_enumerator do
count < 3 ? (count += 1) : false
end
end

# checks that all the non-alias methods were tested
raise "methods not tested: #{methods.inspect}" unless methods.empty?

Expand Down

0 comments on commit e055d2d

Please sign in to comment.