Ticket #11606: highlight_supporting_regexps.patch
| File highlight_supporting_regexps.patch, 2.3 kB (added by artemv, 6 months ago) |
|---|
-
lib/action_view/helpers/text_helper.rb
old new 65 65 # Highlights one or more +phrases+ everywhere in +text+ by inserting it into 66 66 # a +highlighter+ string. The highlighter can be specialized by passing +highlighter+ 67 67 # as a single-quoted string with \1 where the phrase is to be inserted (defaults to 68 # '<strong class="highlight">\1</strong>') 68 # '<strong class="highlight">\1</strong>'). Phrases can include Regexps if you need 69 # to use wildcards. 69 70 # 70 71 # ==== Examples 71 72 # highlight('You searched for: rails', 'rails') 72 73 # # => You searched for: <strong class="highlight">rails</strong> 73 74 # 75 # highlight('You searched for: rails', /\w*o\w*/) 76 # # => <strong class="highlight">You</strong> searched <strong class="highlight">for</strong>: rails 77 # 74 78 # highlight('You searched for: ruby, rails, dhh', 'actionpack') 75 79 # # => You searched for: ruby, rails, dhh 76 80 # … … 83 87 if text.blank? || phrases.blank? 84 88 text 85 89 else 86 match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')90 match = Array(phrases).map { |p| p.is_a?(Regexp) ? p.source : Regexp.escape(p) }.join('|') 87 91 text.gsub(/(#{match})/i, highlighter) 88 92 end 89 93 end -
test/template/text_helper_test.rb
old new 80 80 highlight("This text is not changed because we supplied an empty phrase", nil) 81 81 ) 82 82 83 assert_equal( 84 "This is a <b>beautiful</b> morning, <b>but</b> also a <b>beautiful</b> day", 85 highlight("This is a beautiful morning, but also a beautiful day", /b\w+/, '<b>\1</b>') 86 ) 87 88 assert_equal( 89 "<strong class=\"highlight\">You</strong> searched <strong class=\"highlight\">for</strong>: rails", 90 highlight('You searched for: rails', /\w*o\w*/) 91 ) 92 83 93 assert_equal ' ', highlight(' ', 'blank text is returned verbatim') 84 94 end 85 95