123456789_123456789_123456789_123456789_123456789_

Module: ActionView::Helpers::TextHelper

Overview

Action View Text Helpers

The TextHelper module provides a set of methods for filtering, formatting and transforming strings, which can reduce the amount of inline Ruby code in your views. These helper methods extend Action View making them callable within your template files.

Sanitization

Most text helpers that generate HTML output sanitize the given input by default, 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>"

simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
### => "<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>"

Constant Summary

TagHelper - Included

ARIA_PREFIXES, BOOLEAN_ATTRIBUTES, CLASS_PREFIXES, DATA_PREFIXES, PRE_CONTENT_STRINGS, TAG_TYPES

Class Method Summary

::ActiveSupport::Concern - Extended

class_methods

Define class methods from given block.

included

Evaluate given block in context of base class, so that you can write class macros here.

prepended

Evaluate given block in context of base class, so that you can write class macros here.

append_features, prepend_features

Instance Attribute Summary

Instance Method Summary

TagHelper - Included

#cdata_section

Returns a CDATA section with the given content.

#class_names
#content_tag

Returns an HTML block tag of type name surrounding the content.

#escape_once

Returns an escaped version of html without affecting existing escaped entities.

#tag

Modern syntax.

#token_list

Returns a string of tokens built from args.

#build_tag_values, #ensure_valid_html5_tag_name, #tag_builder

OutputSafetyHelper - Included

#raw

This method outputs without escaping a string.

#safe_join

This method returns an HTML safe string similar to what Array#join would return.

#to_sentence

Converts the array to a comma-separated sentence where the last element is joined by the connector word.

CaptureHelper - Included

#capture

The capture method extracts part of a template as a string object.

#content_for

Calling content_for stores a block of markup in an identifier for later use.

#content_for?

content_for? checks whether any content has been captured yet using content_for.

#provide

The same as content_for but when used with streaming flushes straight back to the layout.

#with_output_buffer

Use an alternate output buffer for the duration of the block.

SanitizeHelper - Included

#sanitize

Sanitizes HTML input, stripping all but known-safe tags and attributes.

#sanitize_css

Sanitizes a block of CSS code.

#strip_links

Strips all link tags from html leaving just the link text.

#strip_tags

Strips all HTML tags from html, including comments and special characters.

Instance Method Details

#concat(string)

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 output text within a non-output code block (i.e., <% %>), you can use the concat method.

<% concat "hello" %> is equivalent to <%= "hello" %>

<%
   unless signed_in?
     concat link_to("Sign In", action: :sign_in)
   end
%>

is equivalent to

<% unless signed_in? %>
  <%= link_to "Sign In", action: :sign_in %>
<% end %>
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 70

def concat(string)
  output_buffer << string
end

#current_cycle(name = "default")

Returns the current cycle string after a cycle has been started. Useful for complex table highlighting or any other design need which requires 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") %>">
    <span style="background-color:<%= current_cycle %>"><%= item %></span>
  </div>
<% end %>
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 509

def current_cycle(name = "default")
  cycle = get_cycle(name)
  cycle.current_value if cycle
end

#cut_excerpt_part(part_position, part, separator, options) (private)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 597

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

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

  if separator != ""
    part = part.split(separator)
    part.delete("")
  end

  affix = part.length > radius ? omission : ""

  part =
    if part_position == :first
      part.last(radius)
    else
      part.first(radius)
    end

  if separator != ""
    part = part.join(separator)
  end

  return affix, part
end

#cycle(first_value, *values)

Creates a TextHelper::Cycle object whose to_s method cycles through elements of an array every time it is called. This can be used for example, to alternate classes for table rows. You can use named cycles to allow nesting in loops. Passing a ::Hash as the last parameter with a :name key will create a named cycle. The default name for a cycle without a :name key is "default". 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.

<%# Alternate CSS classes for even and odd numbers... %>
<% @items = [1,2,3,4] %>
<table>
<% @items.each do |item| %>
  <tr class="<%= cycle("odd", "even") -%>">
    <td><%= item %></td>
  </tr>
<% end %>
</table>

<%# Cycle CSS classes for rows, and text colors for values within each row %>
<% @items = [
  { first: "Robert", middle: "Daniel", last: "James" },
  { first: "Emily", middle: "Shannon", maiden: "Pike", last: "Hicks" },
  { first: "June", middle: "Dae", last: "Jones" },
] %>
<% @items.each do |item| %>
  <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
    <td>
      <% item.values.each do |value| %>
        <%# Create a named cycle "colors" %>
        <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
          <%= value %>
        </span>
      <% end %>
      <% reset_cycle("colors") %>
    </td>
  </tr>
<% end %>
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 483

def cycle(first_value, *values)
  options = values.extract_options!
  name = options.fetch(:name, "default")

  values.unshift(*first_value)

  cycle = get_cycle(name)
  unless cycle && cycle.values == values
    cycle = set_cycle(name, Cycle.new(*values))
  end
  cycle.to_s
end

#excerpt(text, phrase, options = {})

Extracts the first occurrence of phrase plus surrounding text from text. An omission marker is prepended / appended if the start / end of the result does not coincide with the start / end of text. The result is always stripped in any case. Returns nil if phrase isn't found.

Options

:radius : The number of characters (or tokens — see :separator option) around phrase to include in the result. Defaults to 100.

:omission : The marker to prepend / append when the start / end of the excerpt does not coincide with the start / end of text. Defaults to "...".

:separator : The separator between tokens to count for :radius. Defaults to "", which treats each character as a token.

Examples

excerpt('This is an example', 'an', radius: 5)
#### => "...s is an exam..."

excerpt('This is an example', 'is', radius: 5)
#### => "This is a..."

excerpt('This is an example', 'is')
#### => "This is an example"

excerpt('This next thing is an example', 'ex', radius: 2)
#### => "...next..."

excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
#### => "<chop> is also an example"

excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
#### => "...a very beautiful..."
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 270

def excerpt(text, phrase, options = {})
  return unless text && phrase

  separator = options.fetch(:separator, nil) || ""
  case phrase
  when Regexp
    regex = phrase
  else
    regex = /#{Regexp.escape(phrase)}/i
  end

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

  unless separator.empty?
    text.split(separator).each do |value|
      if value.match?(regex)
        phrase = value
        break
      end
    end
  end

  first_part, second_part = text.split(phrase, 2)

  prefix, first_part   = cut_excerpt_part(:first, first_part, separator, options)
  postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)

  affix = [
    first_part,
    !first_part.empty? ? separator : "",
    phrase,
    !second_part.empty? ? separator : "",
    second_part
  ].join.strip

  [prefix, affix, postfix].join
end

#get_cycle(name) (private)

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.

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 579

def get_cycle(name)
  @_cycles = Hash.new unless defined?(@_cycles)
  @_cycles[name]
end

#highlight(text, phrases, options = {}, &block)

Highlights occurrences of phrases in text by formatting them with a highlighter string. phrases can be one or more strings or regular expressions. The result will be marked HTML safe. By default, text is sanitized before highlighting to prevent possible XSS attacks.

The return value is HTML markup. It is safe only as element content where the HTML parser applies the "in body" insertion mode rules, such as inside a

,

or element. Anywhere else it is unsafe or incorrect, including in an attribute value and inside a