Skip to content
This repository
Browse code

Ensure Array#to_sentence does not modify given hash

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...
commit 60571b853920707c1103c5f9659e7b690d8eae73 1 parent 5847f59
Carlos Antonio da Silva authored June 26, 2012
11  activesupport/lib/active_support/core_ext/array/conversions.rb
... ...
@@ -1,6 +1,5 @@
1 1
 require 'active_support/xml_mini'
2 2
 require 'active_support/core_ext/hash/keys'
3  
-require 'active_support/core_ext/hash/reverse_merge'
4 3
 require 'active_support/core_ext/string/inflections'
5 4
 
6 5
 class Array
@@ -62,14 +61,10 @@ def to_sentence(options = {})
62 61
       :last_word_connector => ', and '
63 62
     }
64 63
     if defined?(I18n)
65  
-      namespace = 'support.array.'
66  
-      default_connectors.each_key do |name|
67  
-        i18n_key = (namespace + name.to_s).to_sym
68  
-        default_connectors[name] = I18n.translate i18n_key, :locale => options[:locale]
69  
-      end
  64
+      i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
  65
+      default_connectors.merge!(i18n_connectors)
70 66
     end
71  
-
72  
-    options.reverse_merge! default_connectors
  67
+    options = default_connectors.merge!(options)
73 68
 
74 69
     case length
75 70
     when 0
6  activesupport/test/core_ext/array_ext_test.rb
@@ -90,6 +90,12 @@ def test_one_element_not_same_object
90 90
   def test_one_non_string_element
91 91
     assert_equal '1', [1].to_sentence
92 92
   end
  93
+
  94
+  def test_does_not_modify_given_hash
  95
+    options = { words_connector: ' ' }
  96
+    assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options)
  97
+    assert_equal({ words_connector: ' ' }, options)
  98
+  end
93 99
 end
94 100
 
95 101
 class ArrayExtToSTests < ActiveSupport::TestCase
5  activesupport/test/i18n_test.rb
@@ -97,4 +97,9 @@ def test_to_sentence
97 97
     I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => default_two_words_connector } }
98 98
     I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => default_last_word_connector } }
99 99
   end
  100
+
  101
+  def test_to_sentence_with_empty_i18n_store
  102
+    I18n.backend.store_translations 'empty', {}
  103
+    assert_equal 'a, b, and c', %w[a b c].to_sentence(locale: 'empty')
  104
+  end
100 105
 end

0 notes on commit 60571b8

Please sign in to comment.
Something went wrong with that request. Please try again.