From a0ee428d7df4ffe5332a17731137803d439fbc02 Mon Sep 17 00:00:00 2001 From: Jan Suchal Date: Thu, 17 Dec 2009 15:21:56 +0100 Subject: [PATCH] Added support for ignoring special characters in TextHelper::highlight. --- actionpack/lib/action_view/helpers/text_helper.rb | 12 +++++++++++- actionpack/test/template/text_helper_test.rb | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletions(-) diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index de6a2dd..b83cd35 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -94,6 +94,9 @@ module ActionView # highlight('You searched for: rails', 'rails', :highlighter => '\1') # # => You searched for: rails # + # highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars => true) + # # => Šumné dievčatá + # # You can still use highlight with the old API that accepts the # +highlighter+ as its optional third parameter: # highlight('You searched for: rails', 'rails', '\1') # => You searched for: rails @@ -107,8 +110,15 @@ module ActionView if text.blank? || phrases.blank? text else + haystack = text.clone match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') - text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter]) + if options[:ignore_special_chars] + haystack = ActiveSupport::Multibyte::Chars.new(haystack).normalize(:kd) + match = ActiveSupport::Multibyte::Chars.new(match).normalize(:kd).gsub(/[^\x00-\x7F]+/n, '').gsub(/\w/, '\0[^\x00-\x7F]*') + end + highlighted = haystack.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter]) + highlighted = ActiveSupport::Multibyte::Chars.new(highlighted).normalize(:kc) if options[:ignore_special_chars] + highlighted end end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 715c390..58496b4 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -150,6 +150,13 @@ class TextHelperTest < ActionView::TestCase ) end + def test_highlight_with_special_chars_ignored + assert_equal( + "Ej veru, šumné dievčatá na Slovensku rastú.", + highlight("Ej veru, šumné dievčatá na Slovensku rastú.", ["ŠUMNÉ", "dievcata"], :ignore_special_chars => true) + ) + end + def test_excerpt assert_equal("...is a beautiful morn...", excerpt("This is a beautiful morning", "beautiful", 5)) assert_equal("This is a...", excerpt("This is a beautiful morning", "this", 5)) -- 1.6.4.msysgit.0