text_helper.rb 17.6 KB
Newer Older
1
require 'active_support/core_ext/string/filters'
2
require 'active_support/core_ext/array/extract_options'
3

D
Initial  
David Heinemeier Hansson 已提交
4
module ActionView
R
Rizwan Reza 已提交
5
  # = Action View Text Helpers
D
Initial  
David Heinemeier Hansson 已提交
6
  module Helpers #:nodoc:
7 8
    # The TextHelper module provides a set of methods for filtering, formatting
    # and transforming strings, which can reduce the amount of inline Ruby code in
9
    # your views. These helper methods extend Action View making them callable
10
    # within your template files.
11 12 13 14 15 16 17 18 19 20
    #
    # ==== Sanitization
    #
    # Most text helpers by default sanitize the given content, but do not escape it.
    # This means HTML tags will appear in the page but all malicious code will be removed.
    # Let's look at some examples using the +simple_format+ method:
    #
    #   simple_format('<a href="http://example.com/">Example</a>')
    #   # => "<p><a href=\"http://example.com/\">Example</a></p>"
    #
M
Matt Duncan 已提交
21
    #   simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
22 23 24 25 26 27 28
    #   # => "<p><a>Example</a></p>"
    #
    # If you want to escape all content, you should invoke the +h+ method before
    # calling the text helper.
    #
    #   simple_format h('<a href="http://example.com/">Example</a>')
    #   # => "<p>&lt;a href=\"http://example.com/\"&gt;Example&lt;/a&gt;</p>"
29
    module TextHelper
30 31 32
      extend ActiveSupport::Concern

      include SanitizeHelper
33
      include TagHelper
34 35
      include OutputSafetyHelper

36 37 38
      # The preferred method of outputting text in your views is to use the
      # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
      # do not operate as expected in an eRuby code block. If you absolutely must
39
      # output text within a non-output code block (i.e., <% %>), you can use the concat method.
D
David Heinemeier Hansson 已提交
40
      #
41
      #   <%
42
      #       concat "hello"
43 44
      #       # is the equivalent of <%= "hello" %>
      #
45
      #       if logged_in
46
      #         concat "Logged in!"
47
      #       else
A
AvnerCohen 已提交
48
      #         concat link_to('login', action: :login)
49 50 51
      #       end
      #       # will either display "Logged in!" or a login link
      #   %>
52
      def concat(string)
53
        output_buffer << string
D
Initial  
David Heinemeier Hansson 已提交
54 55
      end

56
      def safe_concat(string)
C
Carlhuda 已提交
57
        output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
58 59
      end

60
      # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
61 62 63
      # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
      # for a total length not exceeding <tt>:length</tt>.
      #
64
      # Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
65
      #
66 67
      # Pass a block if you want to show extra content when the text is truncated.
      #
68 69 70
      # The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
      # +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
      # may produce invalid HTML (such as unbalanced or incomplete tags).
71 72
      #
      #   truncate("Once upon a time in a world far far away")
73
      #   # => "Once upon a time in a world..."
74
      #
A
AvnerCohen 已提交
75
      #   truncate("Once upon a time in a world far far away", length: 17)
76
      #   # => "Once upon a ti..."
77
      #
A
AvnerCohen 已提交
78
      #   truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
79
      #   # => "Once upon a..."
80
      #
A
AvnerCohen 已提交
81
      #   truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
82
      #   # => "And they f... (continued)"
83
      #
84
      #   truncate("<p>Once upon a time in a world far far away</p>")
85 86 87
      #   # => "&lt;p&gt;Once upon a time in a wo..."
      #
      #   truncate("<p>Once upon a time in a world far far away</p>", escape: false)
88
      #   # => "<p>Once upon a time in a wo..."
89 90 91 92
      #
      #   truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
      #   # => "Once upon a time in a wo...<a href="#">Continue</a>"
      def truncate(text, options = {}, &block)
93 94
        if text
          length  = options.fetch(:length, 30)
95

96 97
          content = text.truncate(length, options)
          content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
98 99 100
          content << capture(&block) if block_given? && text.length > length
          content
        end
D
Initial  
David Heinemeier Hansson 已提交
101 102
      end

103
      # Highlights one or more +phrases+ everywhere in +text+ by inserting it into
104
      # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
105
      # as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to
106
      # '<mark>\1</mark>') or passing a block that receives each matched term.
D
David Heinemeier Hansson 已提交
107
      #
108
      #   highlight('You searched for: rails', 'rails')
109
      #   # => You searched for: <mark>rails</mark>
110
      #
111 112 113
      #   highlight('You searched for: rails', /for|rails/)
      #   # => You searched <mark>for</mark>: <mark>rails</mark>
      #
114
      #   highlight('You searched for: ruby, rails, dhh', 'actionpack')
115
      #   # => You searched for: ruby, rails, dhh
116
      #
A
AvnerCohen 已提交
117
      #   highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
118
      #   # => You searched <em>for</em>: <em>rails</em>
119
      #
A
AvnerCohen 已提交
120
      #   highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
121
      #   # => You searched for: <a href="search?q=rails">rails</a>
122 123 124
      #
      #   highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) }
      #   # => You searched for: <a href="search?q=rails">rails</a>
125
      def highlight(text, phrases, options = {})
126
        text = sanitize(text) if options.fetch(:sanitize, true)
127

128
        if text.blank? || phrases.blank?
129
          text || ""
130
        else
131 132 133
          match = Array(phrases).map do |p|
            Regexp === p ? p.to_s : Regexp.escape(p)
          end.join('|')
134 135 136 137 138 139 140

          if block_given?
            text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found }
          else
            highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
            text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
          end
141
        end.html_safe
D
Initial  
David Heinemeier Hansson 已提交
142
      end
143

144 145 146
      # Extracts an excerpt from +text+ that matches the first instance of +phrase+.
      # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
      # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
C
Carson McDonald 已提交
147 148
      # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. Use the
      # <tt>:separator</tt> option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+
149
      # isn't found, nil is returned.
150
      #
A
AvnerCohen 已提交
151
      #   excerpt('This is an example', 'an', radius: 5)
152 153
      #   # => ...s is an exam...
      #
A
AvnerCohen 已提交
154
      #   excerpt('This is an example', 'is', radius: 5)
155 156 157 158 159
      #   # => This is a...
      #
      #   excerpt('This is an example', 'is')
      #   # => This is an example
      #
A
AvnerCohen 已提交
160
      #   excerpt('This next thing is an example', 'ex', radius: 2)
161 162
      #   # => ...next...
      #
A
AvnerCohen 已提交
163
      #   excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
164
      #   # => <chop> is also an example
165
      #
C
Carson McDonald 已提交
166
      #   excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
167
      #   # => ...a very beautiful...
168
      def excerpt(text, phrase, options = {})
169
        return unless text && phrase
170

171
        separator = options.fetch(:separator, nil) || ""
172 173
        case phrase
        when Regexp
174 175
          regex = phrase
        else
176
          regex = /#{Regexp.escape(phrase)}/i
177
        end
178 179 180 181

        return unless matches = text.match(regex)
        phrase = matches[0]

182 183 184 185 186 187
        unless separator.empty?
          text.split(separator).each do |value|
            if value.match(regex)
              regex = phrase = value
              break
            end
188 189
          end
        end
190

191
        first_part, second_part = text.split(phrase, 2)
D
Initial  
David Heinemeier Hansson 已提交
192

193 194
        prefix, first_part   = cut_excerpt_part(:first, first_part, separator, options)
        postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
A
Aaron Patterson 已提交
195

P
Paul Nikitochkin 已提交
196 197
        affix = [first_part, separator, phrase, separator, second_part].join.strip
        [prefix, affix, postfix].join
198
      end
D
Initial  
David Heinemeier Hansson 已提交
199

200 201
      # Attempts to pluralize the +singular+ word unless +count+ is 1. If
      # +plural+ is supplied, it will use that when count is > 1, otherwise
202
      # it will use the Inflector to determine the plural form.
D
David Heinemeier Hansson 已提交
203
      #
204
      #   pluralize(1, 'person')
205 206
      #   # => 1 person
      #
207
      #   pluralize(2, 'person')
208 209
      #   # => 2 people
      #
210
      #   pluralize(3, 'person', 'users')
211 212 213 214
      #   # => 3 users
      #
      #   pluralize(0, 'person')
      #   # => 0 people
D
Initial  
David Heinemeier Hansson 已提交
215
      def pluralize(count, singular, plural = nil)
216 217
        word = if (count == 1 || count =~ /^1(\.0+)?$/)
          singular
218 219 220
        else
          plural || singular.pluralize
        end
221

222
        "#{count || 0} #{word}"
D
Initial  
David Heinemeier Hansson 已提交
223 224
      end

D
David Heinemeier Hansson 已提交
225
      # Wraps the +text+ into lines no longer than +line_width+ width. This method
226 227
      # breaks on the first whitespace character that does not exceed +line_width+
      # (which is 80 by default).
D
David Heinemeier Hansson 已提交
228
      #
229 230 231
      #   word_wrap('Once upon a time')
      #   # => Once upon a time
      #
232
      #   word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
233
      #   # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
234
      #
A
AvnerCohen 已提交
235
      #   word_wrap('Once upon a time', line_width: 8)
236
      #   # => Once\nupon a\ntime
237
      #
A
AvnerCohen 已提交
238
      #   word_wrap('Once upon a time', line_width: 1)
239
      #   # => Once\nupon\na\ntime
240
      def word_wrap(text, options = {})
241
        line_width = options.fetch(:line_width, 80)
242

243
        text.split("\n").collect! do |line|
244
          line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
245
        end * "\n"
246 247
      end

D
David Heinemeier Hansson 已提交
248
      # Returns +text+ transformed into HTML using simple formatting rules.
249
      # Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
D
David Heinemeier Hansson 已提交
250 251
      # paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
      # considered as a linebreak and a <tt><br /></tt> tag is appended. This
252
      # method does not remove the newlines from the +text+.
253
      #
254
      # You can pass any HTML attributes into <tt>html_options</tt>. These
255
      # will be added to all created paragraphs.
256 257 258
      #
      # ==== Options
      # * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
259
      # * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt>
260
      #
261
      # ==== Examples
262
      #   my_text = "Here is some basic text...\n...with a line break."
263 264
      #
      #   simple_format(my_text)
265
      #   # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
266
      #
A
AvnerCohen 已提交
267
      #   simple_format(my_text, {}, wrapper_tag: "div")
268
      #   # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
269
      #
270
      #   more_text = "We want to put a paragraph...\n\n...right there."
271 272
      #
      #   simple_format(more_text)
273
      #   # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
274
      #
A
AvnerCohen 已提交
275
      #   simple_format("Look ma! A class!", class: 'description')
276
      #   # => "<p class='description'>Look ma! A class!</p>"
277
      #
278 279 280 281
      #   simple_format("<blink>Unblinkable.</blink>")
      #   # => "<p>Unblinkable.</p>"
      #
      #   simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
282
      #   # => "<p><blink>Blinkable!</blink> It's true.</p>"
283
      def simple_format(text, html_options = {}, options = {})
284
        wrapper_tag = options.fetch(:wrapper_tag, :p)
285

286
        text = sanitize(text) if options.fetch(:sanitize, true)
A
Avi Tzurel 已提交
287 288 289
        paragraphs = split_paragraphs(text)

        if paragraphs.empty?
290
          content_tag(wrapper_tag, nil, html_options)
A
Avi Tzurel 已提交
291
        else
292
          paragraphs.map! { |paragraph|
293
            content_tag(wrapper_tag, raw(paragraph), html_options)
A
Avi Tzurel 已提交
294 295
          }.join("\n\n").html_safe
        end
296
      end
D
Initial  
David Heinemeier Hansson 已提交
297

D
David Heinemeier Hansson 已提交
298
      # Creates a Cycle object whose _to_s_ method cycles through elements of an
299
      # array every time it is called. This can be used for example, to alternate
300
      # classes for table rows. You can use named cycles to allow nesting in loops.
301
      # Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
302 303 304 305
      # named cycle. The default name for a cycle without a +:name+ key is
      # <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
      # and passing the name of the cycle. The current cycle string can be obtained
      # anytime using the current_cycle method.
306
      #
307 308 309
      #   # Alternate CSS classes for even and odd numbers...
      #   @items = [1,2,3,4]
      #   <table>
D
David Heinemeier Hansson 已提交
310
      #   <% @items.each do |item| %>
311
      #     <tr class="<%= cycle("odd", "even") -%>">
D
David Heinemeier Hansson 已提交
312
      #       <td>item</td>
313
      #     </tr>
D
David Heinemeier Hansson 已提交
314
      #   <% end %>
315
      #   </table>
316 317
      #
      #
318
      #   # Cycle CSS classes for rows, and text colors for values within each row
A
AvnerCohen 已提交
319 320 321
      #   @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'},
      #                {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'},
      #               {first: 'June', middle: 'Dae', last: 'Jones'}]
D
David Heinemeier Hansson 已提交
322
      #   <% @items.each do |item| %>
A
AvnerCohen 已提交
323
      #     <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
324
      #       <td>
D
David Heinemeier Hansson 已提交
325
      #         <% item.values.each do |value| %>
D
David Heinemeier Hansson 已提交
326
      #           <%# Create a named cycle "colors" %>
A
AvnerCohen 已提交
327
      #           <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
328
      #             <%= value %>
329
      #           </span>
D
David Heinemeier Hansson 已提交
330 331
      #         <% end %>
      #         <% reset_cycle("colors") %>
332 333
      #       </td>
      #    </tr>
D
David Heinemeier Hansson 已提交
334
      #  <% end %>
335
      def cycle(first_value, *values)
336
        options = values.extract_options!
337
        name = options.fetch(:name, 'default')
338

339
        values.unshift(*first_value)
340 341

        cycle = get_cycle(name)
A
Aaron Patterson 已提交
342
        unless cycle && cycle.values == values
343 344
          cycle = set_cycle(name, Cycle.new(*values))
        end
A
Aaron Patterson 已提交
345
        cycle.to_s
346
      end
347

348
      # Returns the current cycle string after a cycle has been started. Useful
P
Pratik Naik 已提交
349
      # for complex table highlighting or any other design need which requires
350 351 352 353 354 355
      # the current cycle string in more than one place.
      #
      #   # Alternate background colors
      #   @items = [1,2,3,4]
      #   <% @items.each do |item| %>
      #     <div style="background-color:<%= cycle("red","white","blue") %>">
P
Pratik Naik 已提交
356
      #       <span style="background-color:<%= current_cycle %>"><%= item %></span>
357 358 359 360
      #     </div>
      #   <% end %>
      def current_cycle(name = "default")
        cycle = get_cycle(name)
N
Neeraj Singh 已提交
361
        cycle.current_value if cycle
362 363
      end

364
      # Resets a cycle so that it starts from the first element the next time
D
David Heinemeier Hansson 已提交
365
      # it is called. Pass in +name+ to reset a named cycle.
366 367 368 369 370 371 372
      #
      #   # Alternate CSS classes for even and odd numbers...
      #   @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
      #   <table>
      #   <% @items.each do |item| %>
      #     <tr class="<%= cycle("even", "odd") -%>">
      #         <% item.each do |value| %>
A
AvnerCohen 已提交
373
      #           <span style="color:<%= cycle("#333", "#666", "#999", name: "colors") -%>">
374 375 376 377 378 379 380 381
      #             <%= value %>
      #           </span>
      #         <% end %>
      #
      #         <% reset_cycle("colors") %>
      #     </tr>
      #   <% end %>
      #   </table>
382 383
      def reset_cycle(name = "default")
        cycle = get_cycle(name)
A
Aaron Patterson 已提交
384
        cycle.reset if cycle
385 386
      end

387
      class Cycle #:nodoc:
388
        attr_reader :values
389

390 391 392 393
        def initialize(first_value, *values)
          @values = values.unshift(first_value)
          reset
        end
394

395 396 397 398
        def reset
          @index = 0
        end

399 400 401 402
        def current_value
          @values[previous_index].to_s
        end

403 404
        def to_s
          value = @values[@index].to_s
405
          @index = next_index
406 407
          return value
        end
408 409 410 411 412 413 414 415 416 417 418 419 420 421

        private

        def next_index
          step_index(1)
        end

        def previous_index
          step_index(-1)
        end

        def step_index(n)
          (@index + n) % @values.size
        end
422
      end
423

D
Initial  
David Heinemeier Hansson 已提交
424
      private
425 426 427 428
        # The cycle helpers need to store the cycles in a place that is
        # guaranteed to be reset every time a page is rendered, so it
        # uses an instance variable of ActionView::Base.
        def get_cycle(name)
429
          @_cycles = Hash.new unless defined?(@_cycles)
430 431
          return @_cycles[name]
        end
432

433
        def set_cycle(name, cycle_object)
434
          @_cycles = Hash.new unless defined?(@_cycles)
435 436
          @_cycles[name] = cycle_object
        end
A
Avi Tzurel 已提交
437 438 439 440 441 442 443 444

        def split_paragraphs(text)
          return [] if text.blank?

          text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t|
            t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t
          end
        end
445

446
        def cut_excerpt_part(part_position, part, separator, options)
447 448
          return "", "" unless part

449 450 451
          radius   = options.fetch(:radius, 100)
          omission = options.fetch(:omission, "...")

452 453 454
          part = part.split(separator)
          part.delete("")
          affix = part.size > radius ? omission : ""
455

456 457
          part = if part_position == :first
            drop_index = [part.length - radius, 0].max
458
            part.drop(drop_index)
459
          else
460
            part.first(radius)
461 462
          end

463
          return affix, part.join(separator)
464
        end
D
Initial  
David Heinemeier Hansson 已提交
465 466
    end
  end
467
end