From 667522ca9834ce1f173a3421fb0bf0f555324c6f Mon Sep 17 00:00:00 2001 From: Norman Clarke Date: Fri, 28 May 2010 16:36:22 -0300 Subject: Adds titleize/titlecase to AS::Multibyte::Chars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [#2794 state:resolved] Signed-off-by: José Valim --- activesupport/lib/active_support/multibyte/chars.rb | 10 ++++++++++ activesupport/test/multibyte_chars_test.rb | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index a275176b4a..04193bfa65 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -371,6 +371,16 @@ module ActiveSupport #:nodoc: (slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase end + # Capitalizes the first letter of every word, when possible. + # + # Example: + # "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró" + # "日本語".mb_chars.titleize # => "日本語" + def titleize + chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.apply_mapping $1, :uppercase_mapping }) + end + alias_method :titlecase, :titleize + # Returns the KC normalization of the string by default. NFKC is considered the best normalization form for # passing strings to databases and validations. # diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index f7a5834527..602828ef5f 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -443,6 +443,11 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert_equal 'Abc', 'abc'.mb_chars.capitalize end + def test_titleize_should_work_on_ascii_characters + assert_equal '', ''.mb_chars.titleize + assert_equal 'Abc Abc', 'abc abc'.mb_chars.titleize + end + def test_respond_to_knows_which_methods_the_proxy_responds_to assert ''.mb_chars.respond_to?(:slice) # Defined on Chars assert ''.mb_chars.respond_to?(:capitalize!) # Defined on Chars @@ -480,6 +485,15 @@ class MultibyteCharsExtrasTest < Test::Unit::TestCase end end + def test_titleize_should_be_unicode_aware + assert_equal "Él Que Se Enteró", chars("ÉL QUE SE ENTERÓ").titleize + assert_equal "Абвг Абвг", chars("аБвг аБвг").titleize + end + + def test_titleize_should_not_affect_characters_that_do_not_case_fold + assert_equal "日本語", chars("日本語").titleize + end + def test_limit_should_not_break_on_blank_strings example = chars('') assert_equal example, example.limit(0) -- cgit v1.2.3