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

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  
    6565      # Highlights one or more +phrases+ everywhere in +text+ by inserting it into 
    6666      # a +highlighter+ string. The highlighter can be specialized by passing +highlighter+  
    6767      # 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. 
    6970      # 
    7071      # ==== Examples 
    7172      #   highlight('You searched for: rails', 'rails')   
    7273      #   # => You searched for: <strong class="highlight">rails</strong> 
    7374      # 
     75      #   highlight('You searched for: rails', /\w*o\w*/)   
     76      #   # => <strong class="highlight">You</strong> searched <strong class="highlight">for</strong>: rails 
     77      # 
    7478      #   highlight('You searched for: ruby, rails, dhh', 'actionpack') 
    7579      #   # => You searched for: ruby, rails, dhh  
    7680      # 
     
    8387        if text.blank? || phrases.blank? 
    8488          text 
    8589        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('|') 
    8791          text.gsub(/(#{match})/i, highlighter) 
    8892        end 
    8993      end 
  • test/template/text_helper_test.rb

    old new  
    8080      highlight("This text is not changed because we supplied an empty phrase", nil) 
    8181    ) 
    8282 
     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 
    8393    assert_equal '   ', highlight('   ', 'blank text is returned verbatim') 
    8494  end 
    8595