Skip to content

Commit 4813a0f

Browse files
igordepolliwillianveigarafaelfranca
authored
[ActiveSupport] Add option filter on in_order_of (rails#52072)
* [ActiveSupport] Add option 'filter' on 'in_order_of' * Update activesupport/lib/active_support/core_ext/enumerable.rb Co-authored-by: Willian Gustavo Veiga <[email protected]> --------- Co-authored-by: Willian Gustavo Veiga <[email protected]> Co-authored-by: Rafael Mendonça França <[email protected]>
1 parent 68b6a1c commit 4813a0f

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

activesupport/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
* Add a `filter` option to `in_order_of` to prioritize certain values in the sorting without filtering the results
2+
by these values.
3+
4+
*Igor Depolli*
5+
16
* Improve error message when using `assert_difference` or `assert_changes` with a
27
proc by printing the proc's source code (MRI only).
38

activesupport/lib/active_support/core_ext/enumerable.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,14 @@ def compact_blank
192192
# # => [ Person.find(1), Person.find(5), Person.find(3) ]
193193
#
194194
# If the +series+ include keys that have no corresponding element in the Enumerable, these are ignored.
195-
# If the Enumerable has additional elements that aren't named in the +series+, these are not included in the result.
196-
def in_order_of(key, series)
197-
group_by(&key).values_at(*series).flatten(1).compact
195+
# If the Enumerable has additional elements that aren't named in the +series+, these are not included in the result, unless
196+
# the +filter+ option is set to +false+.
197+
def in_order_of(key, series, filter: true)
198+
if filter
199+
group_by(&key).values_at(*series).flatten(1).compact
200+
else
201+
sort_by { |v| series.index(v.public_send(key)) || series.size }.compact
202+
end
198203
end
199204

200205
# Returns the sole item in the enumerable. If there are no items, or more

activesupport/test/core_ext/enumerable_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,11 @@ def test_in_order_of_preserves_nested_elements
386386
assert_equal [[:opened, { price: 2, currency: :usd }], [:paid, { price: 1, currency: :eur }]], values.in_order_of(:first, [:opened, :paid])
387387
end
388388

389+
def test_in_order_of_with_filter_false
390+
values = [ Payment.new(5), Payment.new(3), Payment.new(1) ]
391+
assert_equal [ Payment.new(1), Payment.new(5), Payment.new(3) ], values.in_order_of(:price, [ 1, 5 ], filter: false)
392+
end
393+
389394
def test_sole
390395
expected_raise = Enumerable::SoleItemExpectedError
391396

0 commit comments

Comments
 (0)