Peter Marklund

Peter Marklund's Home

Wed Sep 17 2008 07:28:14 GMT+0000 (Coordinated Universal Time)

Rails I18n: Array#to_sentence and :skip_last_comma

The Array#to_sentence method in ActiveSupport joins an array into a string with a locale dependent connector such as "and" for english and "och" for swedish. The sentence connector is determined by the I18n message support.array.sentence_connector. The issue is that in english you have a comma before the last connector whereas in swedish you don't. The existance of the last comma is set with the :skip_last_comma option. Ideally we would like this to always be true for the swedish locale. Therefore I added the I18n key support.array.sentence_skip_last_comma and patched the to_sentence method:

class ::Array
  alias_method :to_sentence_orig, :to_sentence
  def to_sentence(options = {})
    extra_options = {}
    skip_last_comma = I18n.translate(:'support.array.sentence_skip_last_comma')
    extra_options[:skip_last_comma] = skip_last_comma if skip_last_comma !~ /translation missing: /
    to_sentence_orig(options.reverse_merge(extra_options))
  end
end

Here is the corresponding spec:

    it "can join array elements with Array#to_sentence" do
      with_locale("en-US") { ["knatte", "fnatte", "tjatte"].to_sentence.should == "knatte, fnatte, and tjatte" }
      with_locale("sv-SE") { ["knatte", "fnatte", "tjatte"].to_sentence.should == "knatte, fnatte och tjatte" }
      with_locale("sv-SE") do
        ["knatte", "fnatte", "tjatte"].to_sentence(:skip_last_comma => false).should == "knatte, fnatte, och tjatte"
      end
    end