Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 534 lines (486 sloc) 22.771 kB
76f024a @fxn adds missing requires for Object#blank? and Object#present?
fxn authored
1 require 'active_support/core_ext/object/blank'
d57397c @dhh Extracted String#truncate from TextHelper#truncate [DHH]
dhh authored
2 require 'active_support/core_ext/string/filters'
0eacdcf @jeremy Use a consistent load path to avoid double requires. Fix some scatter…
jeremy authored
3 require 'action_view/helpers/tag_helper'
9853134 @josh Require missing libraries and check for defined ActionController cons…
josh authored
4
db045db @dhh Initial
dhh authored
5 module ActionView
6 module Helpers #:nodoc:
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
7 # The TextHelper module provides a set of methods for filtering, formatting
8 # and transforming strings, which can reduce the amount of inline Ruby code in
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored
9 # your views. These helper methods extend Action View making them callable
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
10 # within your template files.
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
11 module TextHelper
12 # The preferred method of outputting text in your views is to use the
13 # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
14 # do not operate as expected in an eRuby code block. If you absolutely must
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
15 # output text within a non-output code block (i.e., <% %>), you can use the concat method.
b34ed9b @dhh Docfix (closes #6393)
dhh authored
16 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
17 # ==== Examples
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
18 # <%
4d4c8e2 @jeremy Don't pass block binding to concat
jeremy authored
19 # concat "hello"
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
20 # # is the equivalent of <%= "hello" %>
21 #
8e72fd9 @fxn revises an example in the rdoc of TextHelper#concat
fxn authored
22 # if logged_in
4d4c8e2 @jeremy Don't pass block binding to concat
jeremy authored
23 # concat "Logged in!"
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
24 # else
4d4c8e2 @jeremy Don't pass block binding to concat
jeremy authored
25 # concat link_to('login', :action => login)
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
26 # end
27 # # will either display "Logged in!" or a login link
28 # %>
4cbb9db For performance reasons, you can no longer call html_safe! on Strings…
Yehuda Katz authored
29 def concat(string)
72f93b5 @jeremy Check whether blocks are called from erb using a special __in_erb_tem…
jeremy authored
30 output_buffer << string
db045db @dhh Initial
dhh authored
31 end
32
4cbb9db For performance reasons, you can no longer call html_safe! on Strings…
Yehuda Katz authored
33 def safe_concat(string)
c61ed70 Some more tweaks on <% %>.
Carlhuda authored
34 output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
4cbb9db For performance reasons, you can no longer call html_safe! on Strings…
Yehuda Katz authored
35 end
36
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
37 # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
618771b @stevestmartin Update truncate documentation / examples to more clearly demonstrate …
stevestmartin authored
38 # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
39 # for a total length not exceeding <tt>:length</tt>.
40 #
5e190ef @airblade Truncate helper accepts a :separator for a more legible result [#1807…
airblade authored
41 # Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
a424808 @wincent truncate() should not try to produce HTML-safe output
wincent authored
42 #
43 # The result is not marked as HTML-safe, so will be subject to the default escaping when
44 # used in views, unless wrapped by <tt>raw()</tt>. Care should be taken if +text+ contains HTML tags
45 # or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
46 #
47 # ==== Examples
48 #
49 # truncate("Once upon a time in a world far far away")
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
50 # # => "Once upon a time in a world..."
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
51 #
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
52 # truncate("Once upon a time in a world far far away", :length => 17)
53 # # => "Once upon a ti..."
5e190ef @airblade Truncate helper accepts a :separator for a more legible result [#1807…
airblade authored
54 #
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
55 # truncate("Once upon a time in a world far far away", :lenght => 17, :separator => ' ')
56 # # => "Once upon a..."
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
57 #
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
58 # truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
59 # # => "And they f... (continued)"
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
60 #
27f337d @spastorino truncate documentation an examples added for :safe option
spastorino authored
61 # truncate("<p>Once upon a time in a world far far away</p>")
62 # # => "<p>Once upon a time in a wo..."
63 #
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
64 # You can still use <tt>truncate</tt> with the old API that accepts the
65 # +length+ as its optional second and the +ellipsis+ as its
66 # optional third parameter:
67 # truncate("Once upon a time in a world far far away", 14)
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
68 # # => "Once upon a..."
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
69 #
618771b @stevestmartin Update truncate documentation / examples to more clearly demonstrate …
stevestmartin authored
70 # truncate("And they found that many people were sleeping better.", 25, "... (continued)")
315e895 @fxn revises the documentation of String#truncate and the truncate helper
fxn authored
71 # # => "And they f... (continued)"
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
72 def truncate(text, *args)
73 options = args.extract_options!
74 unless args.empty?
75 ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' +
76 'length and omission arguments', caller)
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
77
7329990 @Manfred Change all calls to String#chars to String#mb_chars. Remove a excepti…
Manfred authored
78 options[:length] = args[0] || 30
79 options[:omission] = args[1] || "..."
607511c @jeremy Ruby 1.9 compat: truncate and excerpt helpers
jeremy authored
80 end
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
81
d57397c @dhh Extracted String#truncate from TextHelper#truncate [DHH]
dhh authored
82 options.reverse_merge!(:length => 30)
83
84 text.truncate(options.delete(:length), options) if text
db045db @dhh Initial
dhh authored
85 end
86
67d5a1a @jeremy Highlight helper highlights one or many terms in a single pass.
jeremy authored
87 # Highlights one or more +phrases+ everywhere in +text+ by inserting it into
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
88 # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
89 # as a single-quoted string with \1 where the phrase is to be inserted (defaults to
90 # '<strong class="highlight">\1</strong>')
b34ed9b @dhh Docfix (closes #6393)
dhh authored
91 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
92 # ==== Examples
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
93 # highlight('You searched for: rails', 'rails')
67d5a1a @jeremy Highlight helper highlights one or many terms in a single pass.
jeremy authored
94 # # => You searched for: <strong class="highlight">rails</strong>
95 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
96 # highlight('You searched for: ruby, rails, dhh', 'actionpack')
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
97 # # => You searched for: ruby, rails, dhh
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
98 #
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
99 # highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>')
67d5a1a @jeremy Highlight helper highlights one or many terms in a single pass.
jeremy authored
100 # # => You searched <em>for</em>: <em>rails</em>
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
101 #
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
102 # highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>')
103 # # => You searched for: <a href="search?q=rails">rails</a>
104 #
105 # You can still use <tt>highlight</tt> with the old API that accepts the
106 # +highlighter+ as its optional third parameter:
107 # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a>
108 def highlight(text, phrases, *args)
109 options = args.extract_options!
110 unless args.empty?
111 options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>'
112 end
113 options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
114
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
115 text = sanitize(text) unless options[:sanitize] == false
67d5a1a @jeremy Highlight helper highlights one or many terms in a single pass.
jeremy authored
116 if text.blank? || phrases.blank?
117 text
118 else
119 match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
3c625d6 @josh Ruby 1.9 compat: removed redundant nested repeat operator
josh authored
120 text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
121 end.html_safe
db045db @dhh Initial
dhh authored
122 end
dfac1ce @dhh Fixed that form helpers would treat string and symbol keys differentl…
dhh authored
123
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
124 # Extracts an excerpt from +text+ that matches the first instance of +phrase+.
125 # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
126 # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
127 # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string
128 # will be stripped in any case. If the +phrase+ isn't found, nil is returned.
129 #
130 # ==== Examples
131 # excerpt('This is an example', 'an', :radius => 5)
132 # # => ...s is an exam...
133 #
134 # excerpt('This is an example', 'is', :radius => 5)
135 # # => This is a...
136 #
137 # excerpt('This is an example', 'is')
138 # # => This is an example
139 #
140 # excerpt('This next thing is an example', 'ex', :radius => 2)
141 # # => ...next...
142 #
143 # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ')
144 # # => <chop> is also an example
145 #
146 # You can still use <tt>excerpt</tt> with the old API that accepts the
147 # +radius+ as its optional third and the +ellipsis+ as its
148 # optional forth parameter:
149 # excerpt('This is an example', 'an', 5) # => ...s is an exam...
150 # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example
151 def excerpt(text, phrase, *args)
152 options = args.extract_options!
153 unless args.empty?
154 options[:radius] = args[0] || 100
155 options[:omission] = args[1] || "..."
156 end
157 options.reverse_merge!(:radius => 100, :omission => "...")
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
158
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
159 if text && phrase
160 phrase = Regexp.escape(phrase)
dfac1ce @dhh Fixed that form helpers would treat string and symbol keys differentl…
dhh authored
161
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
162 if found_pos = text.mb_chars =~ /(#{phrase})/i
163 start_pos = [ found_pos - options[:radius], 0 ].max
164 end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
db045db @dhh Initial
dhh authored
165
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
166 prefix = start_pos > 0 ? options[:omission] : ""
167 postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
db045db @dhh Initial
dhh authored
168
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
169 prefix + text.mb_chars[start_pos..end_pos].strip + postfix
170 else
171 nil
607511c @jeremy Ruby 1.9 compat: truncate and excerpt helpers
jeremy authored
172 end
173 end
b8eec5a @Manfred Remove special 1.9 version of excerpt helper.
Manfred authored
174 end
db045db @dhh Initial
dhh authored
175
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
176 # Attempts to pluralize the +singular+ word unless +count+ is 1. If
177 # +plural+ is supplied, it will use that when count is > 1, otherwise
178 # it will use the Inflector to determine the plural form
b34ed9b @dhh Docfix (closes #6393)
dhh authored
179 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
180 # ==== Examples
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
181 # pluralize(1, 'person')
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
182 # # => 1 person
183 #
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
184 # pluralize(2, 'person')
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
185 # # => 2 people
186 #
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
187 # pluralize(3, 'person', 'users')
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
188 # # => 3 users
189 #
190 # pluralize(0, 'person')
191 # # => 0 people
db045db @dhh Initial
dhh authored
192 def pluralize(count, singular, plural = nil)
b235af7 @gabrielmansour Fix pluralization for numbers formatted like '1.00'
gabrielmansour authored
193 "#{count || 0} " + ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize))
db045db @dhh Initial
dhh authored
194 end
195
b34ed9b @dhh Docfix (closes #6393)
dhh authored
196 # Wraps the +text+ into lines no longer than +line_width+ width. This method
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
197 # breaks on the first whitespace character that does not exceed +line_width+
198 # (which is 80 by default).
b34ed9b @dhh Docfix (closes #6393)
dhh authored
199 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
200 # ==== Examples
201 #
202 # word_wrap('Once upon a time')
203 # # => Once upon a time
204 #
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
205 # 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...')
206 # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined...
207 #
208 # word_wrap('Once upon a time', :line_width => 8)
209 # # => Once upon\na time
210 #
211 # word_wrap('Once upon a time', :line_width => 1)
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
212 # # => Once\nupon\na\ntime
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
213 #
214 # You can still use <tt>word_wrap</tt> with the old API that accepts the
215 # +line_width+ as its optional second parameter:
216 # word_wrap('Once upon a time', 8) # => Once upon\na time
217 def word_wrap(text, *args)
218 options = args.extract_options!
219 unless args.blank?
220 options[:line_width] = args[0] || 80
221 end
222 options.reverse_merge!(:line_width => 80)
223
9686dcd @dhh Fixed TextHelper#word_wrap for multiline strings with extra carrier r…
dhh authored
224 text.split("\n").collect do |line|
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
225 line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line
9686dcd @dhh Fixed TextHelper#word_wrap for multiline strings with extra carrier r…
dhh authored
226 end * "\n"
c608ebe @dhh Added TextHelper#word_wrap(text, line_length = 80) #1449 [tuxie@dekad…
dhh authored
227 end
228
b34ed9b @dhh Docfix (closes #6393)
dhh authored
229 # Returns +text+ transformed into HTML using simple formatting rules.
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
230 # Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
b34ed9b @dhh Docfix (closes #6393)
dhh authored
231 # paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
232 # considered as a linebreak and a <tt><br /></tt> tag is appended. This
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
233 # method does not remove the newlines from the +text+.
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
234 #
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
235 # You can pass any HTML attributes into <tt>html_options</tt>. These
5bf4cbb @technoweenie Allow the #simple_format text_helper to take an html_options hash for…
technoweenie authored
236 # will be added to all created paragraphs.
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
237 # ==== Examples
1b41178 @dhh Docfix (closes #11230) [Henrik N]
dhh authored
238 # my_text = "Here is some basic text...\n...with a line break."
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
239 #
240 # simple_format(my_text)
1b41178 @dhh Docfix (closes #11230) [Henrik N]
dhh authored
241 # # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
242 #
1b41178 @dhh Docfix (closes #11230) [Henrik N]
dhh authored
243 # more_text = "We want to put a paragraph...\n\n...right there."
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
244 #
245 # simple_format(more_text)
1b41178 @dhh Docfix (closes #11230) [Henrik N]
dhh authored
246 # # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
5bf4cbb @technoweenie Allow the #simple_format text_helper to take an html_options hash for…
technoweenie authored
247 #
248 # simple_format("Look ma! A class!", :class => 'description')
249 # # => "<p class='description'>Look ma! A class!</p>"
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
250 def simple_format(text, html_options={}, options={})
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
251 text = ''.html_safe if text.nil?
5bf4cbb @technoweenie Allow the #simple_format text_helper to take an html_options hash for…
technoweenie authored
252 start_tag = tag('p', html_options, true)
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
253 text = sanitize(text) unless options[:sanitize] == false
5bf4cbb @technoweenie Allow the #simple_format text_helper to take an html_options hash for…
technoweenie authored
254 text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n
255 text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph
256 text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
257 text.insert 0, start_tag
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
258 text.html_safe.safe_concat("</p>")
1b93da3 @dhh Added TextHelper#simple_format as a non-dependency text presentation …
dhh authored
259 end
db045db @dhh Initial
dhh authored
260
b047929 @lifo Merge with docrails
lifo authored
261 # Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
262 # will limit what should be linked. You can add HTML attributes to the links using
f97832b @lifo Merge docrails
lifo authored
263 # <tt>:html</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default),
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
264 # <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
265 # e-mail address is yielded and the result is used as the link text.
266 #
267 # ==== Examples
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
268 # auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com")
c92a7ce @dhh Docfix (closes #10493)
dhh authored
269 # # => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
270 # # say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
0369ec7 @dhh Made auto_link the only public method of its clan and added an option…
dhh authored
271 #
b047929 @lifo Merge with docrails
lifo authored
272 # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls)
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
273 # # => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a>
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
274 # # or e-mail david@loudthinking.com"
adba181 @jeremy The auto_link text helper accepts an optional block to format the lin…
jeremy authored
275 #
b047929 @lifo Merge with docrails
lifo authored
276 # auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :email_addresses)
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
277 # # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
b34ed9b @dhh Docfix (closes #6393)
dhh authored
278 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
279 # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com."
f97832b @lifo Merge docrails
lifo authored
280 # auto_link(post_body, :html => { :target => '_blank' }) do |text|
adba181 @jeremy The auto_link text helper accepts an optional block to format the lin…
jeremy authored
281 # truncate(text, 15)
282 # end
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
283 # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>.
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
284 # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>."
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
285 #
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
286 #
287 # You can still use <tt>auto_link</tt> with the old API that accepts the
288 # +link+ as its optional second parameter and the +html_options+ hash
289 # as its optional third parameter:
290 # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com."
291 # auto_link(post_body, :urls) # => Once upon\na time
292 # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\">http://www.myblog.com</a>.
293 # Please e-mail me at me@email.com."
294 #
295 # auto_link(post_body, :all, :target => "_blank") # => Once upon\na time
296 # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.myblog.com</a>.
297 # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>."
f97832b @lifo Merge docrails
lifo authored
298 def auto_link(text, *args, &block)#link = :all, html = {}, &block)
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
299 return ''.html_safe if text.blank?
10d9fe4 @clemens Refactored TextHelper#truncate, highlight, excerpt, word_wrap and aut…
clemens authored
300
301 options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter
302 unless args.empty?
303 options[:link] = args[0] || :all
304 options[:html] = args[1] || {}
305 end
306 options.reverse_merge!(:link => :all, :html => {})
307
308 case options[:link].to_sym
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
309 when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], options, &block), options[:html], &block)
bda55f8 @akaspick allow options to be passed to email address auto generation
akaspick authored
310 when :email_addresses then auto_link_email_addresses(text, options[:html], &block)
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
311 when :urls then auto_link_urls(text, options[:html], options, &block)
0369ec7 @dhh Made auto_link the only public method of its clan and added an option…
dhh authored
312 end
b305756 @dhh Added TextHelper#auto_link, TextHelper#auto_link_urls, and TextHelper…
dhh authored
313 end
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
314
b34ed9b @dhh Docfix (closes #6393)
dhh authored
315 # Creates a Cycle object whose _to_s_ method cycles through elements of an
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
316 # array every time it is called. This can be used for example, to alternate
317 # classes for table rows. You can use named cycles to allow nesting in loops.
318 # Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
319 # named cycle. The default name for a cycle without a +:name+ key is
320 # <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
321 # and passing the name of the cycle. The current cycle string can be obtained
322 # anytime using the current_cycle method.
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
323 #
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
324 # ==== Examples
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
325 # # Alternate CSS classes for even and odd numbers...
326 # @items = [1,2,3,4]
327 # <table>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
328 # <% @items.each do |item| %>
329 # <tr class="<%= cycle("even", "odd") -%>">
330 # <td>item</td>
4d007ce Fix text_helper.rb documentation rendering. Closes #4725. [Frederick …
Marcel Molina authored
331 # </tr>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
332 # <% end %>
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
333 # </table>
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
334 #
335 #
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
336 # # Cycle CSS classes for rows, and text colors for values within each row
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
337 # @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'},
338 # {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'},
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
339 # {:first => 'June', :middle => 'Dae', :last => 'Jones'}]
b34ed9b @dhh Docfix (closes #6393)
dhh authored
340 # <% @items.each do |item| %>
2f3eefc Nitpick: the first value should be odd, second is even.
Ryan Bigg authored
341 # <tr class="<%= cycle("odd", "even", :name => "row_class") -%>">
4d007ce Fix text_helper.rb documentation rendering. Closes #4725. [Frederick …
Marcel Molina authored
342 # <td>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
343 # <% item.values.each do |value| %>
e71465b @dhh Avoid RDoc warning
dhh authored
344 # <%# Create a named cycle "colors" %>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
345 # <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>">
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
346 # <%= value %>
4d007ce Fix text_helper.rb documentation rendering. Closes #4725. [Frederick …
Marcel Molina authored
347 # </span>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
348 # <% end %>
349 # <% reset_cycle("colors") %>
4d007ce Fix text_helper.rb documentation rendering. Closes #4725. [Frederick …
Marcel Molina authored
350 # </td>
351 # </tr>
b34ed9b @dhh Docfix (closes #6393)
dhh authored
352 # <% end %>
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
353 def cycle(first_value, *values)
354 if (values.last.instance_of? Hash)
355 params = values.pop
356 name = params[:name]
357 else
358 name = "default"
359 end
360 values.unshift(first_value)
361
362 cycle = get_cycle(name)
363 if (cycle.nil? || cycle.values != values)
364 cycle = set_cycle(name, Cycle.new(*values))
365 end
366 return cycle.to_s
367 end
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
368
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
369 # Returns the current cycle string after a cycle has been started. Useful
e033b5d @lifo Merge docrails
lifo authored
370 # for complex table highlighting or any other design need which requires
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
371 # the current cycle string in more than one place.
372 #
373 # ==== Example
374 # # Alternate background colors
375 # @items = [1,2,3,4]
376 # <% @items.each do |item| %>
377 # <div style="background-color:<%= cycle("red","white","blue") %>">
6ef3546 @lifo Merge docrails
lifo authored
378 # <span style="background-color:<%= current_cycle %>"><%= item %></span>
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
379 # </div>
380 # <% end %>
381 def current_cycle(name = "default")
382 cycle = get_cycle(name)
383 cycle.current_value unless cycle.nil?
384 end
385
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
386 # Resets a cycle so that it starts from the first element the next time
b34ed9b @dhh Docfix (closes #6393)
dhh authored
387 # it is called. Pass in +name+ to reset a named cycle.
b00e6a9 @dhh Massive documentation update for all helpers (closes #8223, #8177, #8…
dhh authored
388 #
389 # ==== Example
390 # # Alternate CSS classes for even and odd numbers...
391 # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
392 # <table>
393 # <% @items.each do |item| %>
394 # <tr class="<%= cycle("even", "odd") -%>">
395 # <% item.each do |value| %>
396 # <span style="color:<%= cycle("#333", "#666", "#999", :name => "colors") -%>">
397 # <%= value %>
398 # </span>
399 # <% end %>
400 #
401 # <% reset_cycle("colors") %>
402 # </tr>
403 # <% end %>
404 # </table>
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
405 def reset_cycle(name = "default")
406 cycle = get_cycle(name)
71234da @jeremy r4487@asus: jeremy | 2006-04-29 12:21:39 -0700
jeremy authored
407 cycle.reset unless cycle.nil?
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
408 end
409
1c057b7 @jamis Update/clean up AP documentation (rdoc)
jamis authored
410 class Cycle #:nodoc:
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
411 attr_reader :values
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
412
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
413 def initialize(first_value, *values)
414 @values = values.unshift(first_value)
415 reset
416 end
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
417
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
418 def reset
419 @index = 0
420 end
421
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
422 def current_value
423 @values[previous_index].to_s
424 end
425
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
426 def to_s
427 value = @values[@index].to_s
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
428 @index = next_index
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
429 return value
430 end
f277e1d @metaskills Added TextHelper#current_cycle to return the current cycle for better…
metaskills authored
431
432 private
433
434 def next_index
435 step_index(1)
436 end
437
438 def previous_index
439 step_index(-1)
440 end
441
442 def step_index(n)
443 (@index + n) % @values.size
444 end
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
445 end
da0725a @technoweenie move TextHelper#sanitize config options to the TextHelper module so i…
technoweenie authored
446
db045db @dhh Initial
dhh authored
447 private
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
448 # The cycle helpers need to store the cycles in a place that is
449 # guaranteed to be reset every time a page is rendered, so it
450 # uses an instance variable of ActionView::Base.
451 def get_cycle(name)
71234da @jeremy r4487@asus: jeremy | 2006-04-29 12:21:39 -0700
jeremy authored
452 @_cycles = Hash.new unless defined?(@_cycles)
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
453 return @_cycles[name]
454 end
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
455
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
456 def set_cycle(name, cycle_object)
71234da @jeremy r4487@asus: jeremy | 2006-04-29 12:21:39 -0700
jeremy authored
457 @_cycles = Hash.new unless defined?(@_cycles)
2fe8610 @dhh Added TextHelper#cycle to cycle over an array of values on each hit (…
dhh authored
458 @_cycles[name] = cycle_object
459 end
8e82e29 @madrobby Make TextHelper::auto_link recognize URLs with colons in path correct…
madrobby authored
460
bdf91d6 @jamis Make auto_link parse a greater subset of valid url formats.
jamis authored
461 AUTO_LINK_RE = %r{
133ada6 @mislav auto_link: support arbitrary URI schemes like "ftp:" and "file:"
mislav authored
462 (?: ([\w+.:-]+:)// | www\. )
c6c5cd5 @mislav refactor autolink helper. change tests to expect HTML-escaped URLs
mislav authored
463 [^\s<]+
8f0b213 @mislav avoid auto_linking already linked emails; more robust detection of li…
mislav authored
464 }x
465
466 # regexps for determining context, used high-volume
467 AUTO_LINK_CRE = [/<[^>]+$/, /^[^>]*>/, /<a\b.*?>/i, /<\/a>/i]
468
469 AUTO_EMAIL_RE = /[\w.!#\$%+-]+@[\w-]+(?:\.[\w-]+)+/
b97f4e4 @jamis Fix autolinking to not include trailing tags as part of the URL
jamis authored
470
4f984c9 @mislav auto_link helper: add intelligent ending closing bracket handling. ad…
mislav authored
471 BRACKETS = { ']' => '[', ')' => '(', '}' => '{' }
472
adba181 @jeremy The auto_link text helper accepts an optional block to format the lin…
jeremy authored
473 # Turns all urls into clickable links. If a block is given, each url
b34ed9b @dhh Docfix (closes #6393)
dhh authored
474 # is yielded and the result is used as the link text.
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
475 def auto_link_urls(text, html_options = {}, options = {})
c6c5cd5 @mislav refactor autolink helper. change tests to expect HTML-escaped URLs
mislav authored
476 link_attributes = html_options.stringify_keys
b97f4e4 @jamis Fix autolinking to not include trailing tags as part of the URL
jamis authored
477 text.gsub(AUTO_LINK_RE) do
133ada6 @mislav auto_link: support arbitrary URI schemes like "ftp:" and "file:"
mislav authored
478 scheme, href = $1, $&
11bac70 @cainlevy Ensure auto_link does not ignore multiple trailing punctuations [#250…
cainlevy authored
479 punctuation = []
8f0b213 @mislav avoid auto_linking already linked emails; more robust detection of li…
mislav authored
480
481 if auto_linked?($`, $')
e033b5d @lifo Merge docrails
lifo authored
482 # do not change string; URL is already linked
4f984c9 @mislav auto_link helper: add intelligent ending closing bracket handling. ad…
mislav authored
483 href
484 else
485 # don't include trailing punctuation character as part of the URL
11bac70 @cainlevy Ensure auto_link does not ignore multiple trailing punctuations [#250…
cainlevy authored
486 while href.sub!(/[^\w\/-]$/, '')
487 punctuation.push $&
488 if opening = BRACKETS[punctuation.last] and href.scan(opening).size > href.scan(punctuation.last).size
489 href << punctuation.pop
490 break
4f984c9 @mislav auto_link helper: add intelligent ending closing bracket handling. ad…
mislav authored
491 end
c6c5cd5 @mislav refactor autolink helper. change tests to expect HTML-escaped URLs
mislav authored
492 end
493
494 link_text = block_given?? yield(href) : href
133ada6 @mislav auto_link: support arbitrary URI schemes like "ftp:" and "file:"
mislav authored
495 href = 'http://' + href unless scheme
c6c5cd5 @mislav refactor autolink helper. change tests to expect HTML-escaped URLs
mislav authored
496
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
497 unless options[:sanitize] == false
498 link_text = sanitize(link_text)
499 href = sanitize(href)
500 end
501 content_tag(:a, link_text, link_attributes.merge('href' => href), !!options[:sanitize]) + punctuation.reverse.join('')
480150e @dhh Fixed autolinking to work better in more cases #1013 [Jamis Buck]
dhh authored
502 end
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
503 end.html_safe
0369ec7 @dhh Made auto_link the only public method of its clan and added an option…
dhh authored
504 end
505
adba181 @jeremy The auto_link text helper accepts an optional block to format the lin…
jeremy authored
506 # Turns all email addresses into clickable links. If a block is given,
507 # each email is yielded and the result is used as the link text.
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
508 def auto_link_email_addresses(text, html_options = {}, options = {})
8f0b213 @mislav avoid auto_linking already linked emails; more robust detection of li…
mislav authored
509 text.gsub(AUTO_EMAIL_RE) do
510 text = $&
603c853 @josh Don't fallback to just adding "'s" in TextHelper#pluralize, because t…
josh authored
511
8f0b213 @mislav avoid auto_linking already linked emails; more robust detection of li…
mislav authored
512 if auto_linked?($`, $')
ab764ec @spastorino Makes text_helper methods sanitize the input if the input is not safe…
spastorino authored
513 text.html_safe
09e76e6 @jeremy Autolink behaves well with emails embedded in URLs. Closes #7313.
jeremy authored
514 else
515 display_text = (block_given?) ? yield(text) : text
84d387b @spastorino Make text_helpers methods which return valid html to return it as saf…
spastorino authored
516
517 unless options[:sanitize] == false
518 text = sanitize(text)
519 display_text = sanitize(display_text) unless text == display_text
520 end
bda55f8 @akaspick allow options to be passed to email address auto generation
akaspick authored
521 mail_to text, display_text, html_options
09e76e6 @jeremy Autolink behaves well with emails embedded in URLs. Closes #7313.
jeremy authored
522 end
adba181 @jeremy The auto_link text helper accepts an optional block to format the lin…
jeremy authored
523 end
0369ec7 @dhh Made auto_link the only public method of its clan and added an option…
dhh authored
524 end
8f0b213 @mislav avoid auto_linking already linked emails; more robust detection of li…
mislav authored
525
526 # Detects already linked context or position in the middle of a tag
527 def auto_linked?(left, right)
528 (left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or
529 (left.rindex(AUTO_LINK_CRE[2]) and $' !~ AUTO_LINK_CRE[3])
530 end
db045db @dhh Initial
dhh authored
531 end
532 end
d3ec1d3 @rmanalan auto_link view helper was failing on URLs with colons after a query p…
rmanalan authored
533 end
Something went wrong with that request. Please try again.