Skip to content

Commit

Permalink
Accept single values as a :columns for enumerators
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed May 5, 2024
1 parent 87def54 commit ddf1e33
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## master (unreleased)

- Accept single values as a `:columns` for enumerators
- Add `around_iteration` hook

## 0.3.0 (2023-05-20)
Expand Down
3 changes: 2 additions & 1 deletion lib/sidekiq_iteration/active_record_enumerator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ def initialize(relation, columns: nil, batch_size: 100, order: :asc, cursor: nil
end

@primary_key = "#{relation.table_name}.#{relation.primary_key}"
@columns = Array(columns&.map(&:to_s) || @primary_key)
columns ||= @primary_key
@columns = Array(columns).map(&:to_s)
@primary_key_index = @columns.index(@primary_key) || @columns.index(relation.primary_key)
@pluck_columns = if @primary_key_index
@columns
Expand Down
2 changes: 1 addition & 1 deletion lib/sidekiq_iteration/enumerators.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def array_enumerator(array, cursor:)
#
# @param scope [ActiveRecord::Relation] scope to iterate
# @param cursor [Object] offset to start iteration from, usually an id
# @option options :columns [Array<String, Symbol>] used to build the actual query for iteration,
# @option options :columns [Array<String, Symbol>, String, Symbol] used to build the actual query for iteration,
# defaults to primary key
# @option options :batch_size [Integer] (100) size of the batch
# @option options :order [:asc, :desc] (:asc) specifies iteration order
Expand Down
9 changes: 8 additions & 1 deletion test/active_record_enumerator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,20 @@ class ActiveRecordEnumeratorTest < TestCase
assert_equal([products, products.last.id], enum.first)
end

test "columns are configurable" do
test "single column as array" do
enum = build_enumerator(columns: [:updated_at]).batches
products = Product.order(:updated_at).take(2)

assert_equal([products, products.last.updated_at.strftime(SQL_TIME_FORMAT)], enum.first)
end

test "single column as symbol" do
enum = build_enumerator(columns: :updated_at).batches
products = Product.order(:updated_at).take(2)

assert_equal([products, products.last.updated_at.strftime(SQL_TIME_FORMAT)], enum.first)
end

test "multiple columns" do
enum = build_enumerator(columns: [:updated_at, :id]).batches
products = Product.order(:updated_at, :id).take(2)
Expand Down

0 comments on commit ddf1e33

Please sign in to comment.