From adea6b557c9879daa4c0639dd6f873f872f8e173 Mon Sep 17 00:00:00 2001 From: Chris Gunther Date: Thu, 9 Jun 2022 11:40:11 -0400 Subject: [PATCH] Allow proc as group_method for grouped collection select Since Rails v5.2, the group method could be a callable object. --- CHANGELOG.md | 1 + .../inputs/grouped_collection_select_input.rb | 2 +- test/inputs/grouped_collection_select_input_test.rb | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6541713..ba72e6ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ * Add support for Rails 7.0 and Ruby 3.1 (no changes required) * Fix escaping issue on boolean input with `include_hidden: false` and custom wrapper. * Update Bootstrap install generator version 5. [@mhw](https://github.com/mhw) +* Accept proc as `group_method` for grouped collection select ## 5.1.0 diff --git a/lib/simple_form/inputs/grouped_collection_select_input.rb b/lib/simple_form/inputs/grouped_collection_select_input.rb index b6f23bae..2d983d29 100644 --- a/lib/simple_form/inputs/grouped_collection_select_input.rb +++ b/lib/simple_form/inputs/grouped_collection_select_input.rb @@ -23,7 +23,7 @@ module SimpleForm # Sample collection def collection - @collection ||= grouped_collection.map { |collection| collection.try(:send, group_method) }.detect(&:present?) || [] + @collection ||= grouped_collection.map { |collection| group_method.respond_to?(:call) ? group_method.call(collection) : collection.try(:send, group_method) }.detect(&:present?) || [] end def group_method diff --git a/test/inputs/grouped_collection_select_input_test.rb b/test/inputs/grouped_collection_select_input_test.rb index 50e13a9c..85f5ab74 100644 --- a/test/inputs/grouped_collection_select_input_test.rb +++ b/test/inputs/grouped_collection_select_input_test.rb @@ -66,6 +66,19 @@ class GroupedCollectionSelectInputTest < ActionView::TestCase end end + test 'grouped collection allows overriding group_method using a lambda' do + with_input_for @user, :tag_ids, :grouped_select, + collection: { Authors: %w[Jose Carlos] }, + group_method: ->(i) { i.last } + + assert_select 'select.grouped_select#user_tag_ids' do + assert_select 'optgroup[label=Authors]' do + assert_select 'option[value=Jose]', 'Jose' + assert_select 'option[value=Carlos]', 'Carlos' + end + end + end + test 'grouped collection accepts group_label_method option' do with_input_for @user, :tag_ids, :grouped_select, collection: { %w[Jose Carlos] => 'Authors' },