From d72e122b0c994569152e6e4af722897feb337e71 Mon Sep 17 00:00:00 2001 From: Christoph Dibiasi Date: Sun, 24 Aug 2008 00:39:52 +0200 Subject: [PATCH] value_method and text_method in options_from_collection_for_select are chainable --- .../lib/action_view/helpers/form_options_helper.rb | 9 ++++++++- .../test/template/form_options_helper_test.rb | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletions(-) diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 9aae945..290ffb3 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -207,10 +207,17 @@ module ActionView # options_from_collection_for_select(@project.people, "id", "name") # # + # If you provide +value_method+ or +text_method+ as an array, it will chain the elements together. This is especially + # useful when dealing with ActiveRecord associations. Imagine a CapitalCity Model associated with a State: + # options_from_collection_for_select(CapitalCity.all, "id", ["state", "name", "capitalize"]) + # + # # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. def options_from_collection_for_select(collection, value_method, text_method, selected = nil) options = collection.map do |element| - [element.send(text_method), element.send(value_method)] + text_result = text_method.respond_to? :inject ? text_method.inject(element) { |memo, n| memo.send(n) } : element.send(value_method) + value_result = value_method.respond_to? :inject ? value_method.inject(element) { |memo, n| memo.send(n) } : element.send(value_method) + [text_result, value_result] end options_for_select(options, selected) end diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index a33eb85..3dcbe08 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -36,6 +36,18 @@ uses_mocha "FormOptionsHelperTest" do ) end + def test_collection_options_with_chained_methods + @posts = [ + Post.new(" went home", "\n\r ", "To a little house", "shh!"), + Post.new("Babe went home", " Babe", "To a little house", "shh!"), + Post.new("Cabe went home", "\n\nCabe ", "To a little house", "shh!") + ] + + assert_dom_equal( + "\n\n", + options_from_collection_for_select(@posts, ["author_name", "downcase", "strip"], ["title", "upcase"]) + ) + end def test_collection_options_with_preselected_value @posts = [ -- 1.5.5.3