From 9baedc8a963e5efc92911f32a84bc8b74a15a2e9 Mon Sep 17 00:00:00 2001 From: Neil Matatall Date: Tue, 15 Mar 2016 09:22:11 -1000 Subject: mimic ActiveSupport's Array#to_sentence in an html_safe-aware way --- .../action_view/helpers/output_safety_helper.rb | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'actionview/lib/action_view/helpers') diff --git a/actionview/lib/action_view/helpers/output_safety_helper.rb b/actionview/lib/action_view/helpers/output_safety_helper.rb index c0fc3b820f..d4b55423a8 100644 --- a/actionview/lib/action_view/helpers/output_safety_helper.rb +++ b/actionview/lib/action_view/helpers/output_safety_helper.rb @@ -33,6 +33,36 @@ module ActionView #:nodoc: array.flatten.map! { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe end + + # Converts the array to a comma-separated sentence where the last element is + # joined by the connector word. This is the html_safe-aware version of + # ActiveSupport's {Array#to_sentence}[http://api.rubyonrails.org/classes/Array.html#method-i-to_sentence]. + # + def to_sentence(array, options = {}) + options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) + + default_connectors = { + :words_connector => ', ', + :two_words_connector => ' and ', + :last_word_connector => ', and ' + } + if defined?(I18n) + i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {}) + default_connectors.merge!(i18n_connectors) + end + options = default_connectors.merge!(options) + + case array.length + when 0 + ''.html_safe + when 1 + ERB::Util.html_escape(array[0]) + when 2 + safe_join([array[0], array[1]], options[:two_words_connector]) + else + safe_join([safe_join(array[0...-1], options[:words_connector]), options[:last_word_connector], array[-1]]) + end + end end end end -- cgit v1.2.3