Module | ActionView::Helpers::TextHelper |
In: |
vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb
|
Provides a set of methods for working with text strings that can help unburden the level of inline Ruby code in the templates. In the example below we iterate over a collection of posts provided to the template and print each title after making sure it doesn’t run longer than 20 characters:
<% for post in @posts %> Title: <%= truncate(post.title, 20) %> <% end %>
VERBOTEN_TAGS | = | %w(form script) unless defined?(VERBOTEN_TAGS) |
VERBOTEN_ATTRS | = | /^on/i unless defined?(VERBOTEN_ATTRS) |
AUTO_LINK_RE | = | / ( # leading text <\w+.*?>| # leading HTML tag, or [^=!:'"\/]| # leading punctuation, or ^ # beginning of line ) ( (?:http[s]?:\/\/)| # protocol spec, or (?:www\.) # www.* ) ( ([\w]+:?[=?&\/.-]?)* # url segment \w+[\/]? # url tail (?:\#\w*)? # trailing anchor ) ([[:punct:]]|\s|<|$) # trailing text /x unless const_defined?(:AUTO_LINK_RE) |
Turns all urls and email addresses into clickable links. The link parameter can limit what should be linked. Options are :all (default), :email_addresses, and :urls.
Example:
auto_link("Go to http://www.rubyonrails.com and say hello to david@loudthinking.com") => Go to <a href="http://www.rubyonrails.com">http://www.rubyonrails.com</a> and say hello to <a href="mailto:david@loudthinking.com">david@loudthinking.com</a>
If a block is given, each url and email address is yielded and the result is used as the link text. Example:
auto_link(post.body, :all, :target => '_blank') do |text| truncate(text, 15) end
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 144 144: def auto_link(text, link = :all, href_options = {}, &block) 145: return '' if text.blank? 146: case link 147: when :all then auto_link_urls(auto_link_email_addresses(text, &block), href_options, &block) 148: when :email_addresses then auto_link_email_addresses(text, &block) 149: when :urls then auto_link_urls(text, href_options, &block) 150: end 151: end
The regular puts and print are outlawed in eRuby. It’s recommended to use the <%= "hello" %> form instead of print "hello". If you absolutely must use a method-based output, you can use concat. It’s used like this: <% concat "hello", binding %>. Notice that it doesn’t have an equal sign in front. Using <%= concat "hello" %> would result in a double hello.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 15 15: def concat(string, binding) 16: eval("_erbout", binding).concat(string) 17: end
Returns a Cycle object whose to_s value cycles through items of an array every time it is called. This can be used to alternate classes for table rows:
<%- for item in @items do -%> <tr class="<%= cycle("even", "odd") %>"> ... use item ... </tr> <%- end -%>
You can use named cycles to prevent clashes in nested loops. You‘ll have to reset the inner cycle, manually:
<%- for item in @items do -%> <tr class="<%= cycle("even", "odd", :name => "row_class") <td> <%- for value in item.values do -%> <span style="color:'<%= cycle("red", "green", "blue" :name => "colors") %>'"> item </span> <%- end -%> <%- reset_cycle("colors") -%> </td> </tr> <%- end -%>
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 260 260: def cycle(first_value, *values) 261: if (values.last.instance_of? Hash) 262: params = values.pop 263: name = params[:name] 264: else 265: name = "default" 266: end 267: values.unshift(first_value) 268: 269: cycle = get_cycle(name) 270: if (cycle.nil? || cycle.values != values) 271: cycle = set_cycle(name, Cycle.new(*values)) 272: end 273: return cycle.to_s 274: end
Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius. If the phrase isn’t found, nil is returned. Ex:
excerpt("hello my world", "my", 3) => "...lo my wo..."
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 44 44: def excerpt(text, phrase, radius = 100, excerpt_string = "...") 45: if text.nil? || phrase.nil? then return end 46: phrase = Regexp.escape(phrase) 47: 48: if found_pos = text =~ /(#{phrase})/i 49: start_pos = [ found_pos - radius, 0 ].max 50: end_pos = [ found_pos + phrase.length + radius, text.length ].min 51: 52: prefix = start_pos > 0 ? excerpt_string : "" 53: postfix = end_pos < text.length ? excerpt_string : "" 54: 55: prefix + text[start_pos..end_pos].strip + postfix 56: else 57: nil 58: end 59: end
Highlights the phrase where it is found in the text by surrounding it like <strong class="highlight">I’m a highlight phrase</strong>. The highlighter can be specialized by passing highlighter as single-quoted string with \1 where the phrase is supposed to be inserted. N.B.: The phrase is sanitized to include only letters, digits, and spaces before use.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 36 36: def highlight(text, phrase, highlighter = '<strong class="highlight">\1</strong>') 37: if phrase.blank? then return text end 38: text.gsub(/(#{Regexp.escape(phrase)})/i, highlighter) unless text.nil? 39: end
Returns the text with all the Markdown codes turned into HTML-tags. This method is only available if BlueCloth can be required.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 111 111: def markdown(text) 112: text.blank? ? "" : BlueCloth.new(text).to_html 113: end
Attempts to pluralize the singular word unless count is 1. See source for pluralization rules.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 62 62: def pluralize(count, singular, plural = nil) 63: "#{count} " + if count == 1 64: singular 65: elsif plural 66: plural 67: elsif Object.const_defined?("Inflector") 68: Inflector.pluralize(singular) 69: else 70: singular + "s" 71: end 72: end
Resets a cycle so that it starts from the first element in the array the next time it is used.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 278 278: def reset_cycle(name = "default") 279: cycle = get_cycle(name) 280: return if cycle.nil? 281: cycle.reset 282: end
Sanitizes the given HTML by making form and script tags into regular text, and removing all "onxxx" attributes (so that arbitrary Javascript cannot be executed). Also removes href attributes that start with "javascript:".
Returns the sanitized text.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 180 180: def sanitize(html) 181: # only do this if absolutely necessary 182: if html.index("<") 183: tokenizer = HTML::Tokenizer.new(html) 184: new_text = "" 185: 186: while token = tokenizer.next 187: node = HTML::Node.parse(nil, 0, 0, token, false) 188: new_text << case node 189: when HTML::Tag 190: if VERBOTEN_TAGS.include?(node.name) 191: node.to_s.gsub(/</, "<") 192: else 193: if node.closing != :close 194: node.attributes.delete_if { |attr,v| attr =~ VERBOTEN_ATTRS } 195: if node.attributes["href"] =~ /^javascript:/i 196: node.attributes.delete "href" 197: end 198: end 199: node.to_s 200: end 201: else 202: node.to_s.gsub(/</, "<") 203: end 204: end 205: 206: html = new_text 207: end 208: 209: html 210: end
Returns text transformed into HTML using very simple formatting rules Surrounds paragraphs with <p> tags, and converts line breaks into <br/> Two consecutive newlines(\n\n) are considered as a paragraph, one newline (\n) is considered a linebreak, three or more consecutive newlines are turned into two newlines
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 122 122: def simple_format(text) 123: text.gsub!(/(\r\n|\n|\r)/, "\n") # lets make them newlines crossplatform 124: text.gsub!(/\n\n+/, "\n\n") # zap dupes 125: text.gsub!(/\n\n/, '</p>\0<p>') # turn two newlines into paragraph 126: text.gsub!(/([^\n])(\n)([^\n])/, '\1\2<br />\3') # turn single newline into <br /> 127: 128: content_tag("p", text) 129: end
Turns all links into words, like "<a href="something">else</a>" to "else".
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 154 154: def strip_links(text) 155: text.gsub(/<a.*>(.*)<\/a>/m, '\1') 156: end
Strips all HTML tags from the input, including comments. This uses the html-scanner tokenizer and so it’s HTML parsing ability is limited by that of html-scanner.
Returns the tag free text.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 216 216: def strip_tags(html) 217: if html.index("<") 218: text = "" 219: tokenizer = HTML::Tokenizer.new(html) 220: 221: while token = tokenizer.next 222: node = HTML::Node.parse(nil, 0, 0, token, false) 223: # result is only the content of any Text nodes 224: text << node.to_s if node.class == HTML::Text 225: end 226: # strip any comments, and if they have a newline at the end (ie. line with 227: # only a comment) strip that too 228: text.gsub(/<!--(.*?)-->[\n]?/m, "") 229: else 230: html # already plain text 231: end 232: end
Returns the text with all the Textile codes turned into HTML-tags. This method is only available if RedCloth can be required.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 84 84: def textilize(text) 85: if text.blank? 86: "" 87: else 88: textilized = RedCloth.new(text, [ :hard_breaks ]) 89: textilized.hard_breaks = true if textilized.respond_to?("hard_breaks=") 90: textilized.to_html 91: end 92: end
Returns the text with all the Textile codes turned into HTML-tags, but without the regular bounding <p> tag. This method is only available if RedCloth can be required.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 96 96: def textilize_without_paragraph(text) 97: textiled = textilize(text) 98: if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end 99: if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end 100: return textiled 101: end
Truncates text to the length of length and replaces the last three characters with the truncate_string if the text is longer than length.
# File vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb, line 21 21: def truncate(text, length = 30, truncate_string = "...") 22: if text.nil? then return end 23: l = length - truncate_string.length 24: if $KCODE == "NONE" 25: text.length > length ? text[0...l] + truncate_string : text 26: else 27: chars = text.split(//) 28: chars.length > length ? chars[0...l].join + truncate_string : text 29: end 30: end