Skip to content

Commit

Permalink
Ensure Array#to_sentence does not modify given hash
Browse files Browse the repository at this point in the history
Also simplify I18n logic for Array#to_sentence, doing only one lookup
for all keys and using merge!, instead of one lookup for each option key.
  • Loading branch information
carlosantoniodasilva committed Jun 27, 2012
1 parent 5847f59 commit 60571b8
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
11 changes: 3 additions & 8 deletions activesupport/lib/active_support/core_ext/array/conversions.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
require 'active_support/xml_mini'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/string/inflections'

class Array
Expand Down Expand Up @@ -62,14 +61,10 @@ def to_sentence(options = {})
:last_word_connector => ', and '
}
if defined?(I18n)
namespace = 'support.array.'
default_connectors.each_key do |name|
i18n_key = (namespace + name.to_s).to_sym
default_connectors[name] = I18n.translate i18n_key, :locale => options[:locale]
end
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
default_connectors.merge!(i18n_connectors)
end

options.reverse_merge! default_connectors
options = default_connectors.merge!(options)

case length
when 0
Expand Down
6 changes: 6 additions & 0 deletions activesupport/test/core_ext/array_ext_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ def test_one_element_not_same_object
def test_one_non_string_element
assert_equal '1', [1].to_sentence
end

def test_does_not_modify_given_hash
options = { words_connector: ' ' }
assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options)
assert_equal({ words_connector: ' ' }, options)
end
end

class ArrayExtToSTests < ActiveSupport::TestCase
Expand Down
5 changes: 5 additions & 0 deletions activesupport/test/i18n_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,9 @@ def test_to_sentence
I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => default_two_words_connector } }
I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => default_last_word_connector } }
end

def test_to_sentence_with_empty_i18n_store
I18n.backend.store_translations 'empty', {}
assert_equal 'a, b, and c', %w[a b c].to_sentence(locale: 'empty')
end
end

0 comments on commit 60571b8

Please sign in to comment.