Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7400: make_highlight_helper_multibyte_safe.2.diff

File make_highlight_helper_multibyte_safe.2.diff, 1.9 kB (added by manfred, 2 years ago)
  • test/template/text_helper_test.rb

    old new  
    6565      "This text is not changed because we supplied an empty phrase", 
    6666      highlight("This text is not changed because we supplied an empty phrase", nil) 
    6767    ) 
     68     
     69    with_kcode 'u' do 
     70      assert_equal( 
     71        "This is a nice <strong class=\"highlight\">café</strong>, but also an expensive <strong class=\"highlight\">café</strong>.", 
     72        highlight("This is a nice café, but also an expensive café.", "café") 
     73      ) 
     74         
     75      assert_equal( 
     76        "This is a nice <strong class=\"highlight\">café</strong>, but also an expensive <strong class=\"highlight\">café</strong>.", 
     77        highlight("This is a nice café, but also an expensive café.", "CAFÉ") 
     78      ) 
     79    end 
    6880  end 
    6981 
    7082  def test_highlighter_with_regexp 
  • lib/action_view/helpers/text_helper.rb

    old new  
    4444      #   highlight('You searched for: rails', 'rails')   
    4545      #    => You searched for: <strong class="highlight">rails</strong> 
    4646      def highlight(text, phrase, highlighter = '<strong class="highlight">\1</strong>') 
    47         if phrase.blank? then return text end 
    48         text.gsub(/(#{Regexp.escape(phrase)})/i, highlighter) unless text.nil? 
     47        return text if phrase.blank? 
     48        phrase = phrase.split(//u).map do |x| 
     49          uc = x.chars.upcase 
     50          dc = x.chars.downcase 
     51          uc == dc ? Regexp.escape(x) : "[#{uc}#{dc}]" 
     52        end.join if phrase.is_utf8? 
     53        text.gsub(/(#{phrase})/, highlighter) unless text.nil? 
    4954      end 
    5055 
    5156      # Extracts an excerpt from +text+ that matches the first instance of +phrase+.