Skip to content

Commit

Permalink
[padrino-helpers] Added support for simple_format, pluralize, truncat…
Browse files Browse the repository at this point in the history
…e, and word_wrap
  • Loading branch information
nesquena committed Nov 25, 2009
1 parent fa5dd69 commit e37c21c
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.rdoc
Expand Up @@ -435,6 +435,19 @@ passing javascript information from a js template to a javascript function.

There is also an alias for escape_html called <tt>h</tt> for even easier usage within templates.

Format helpers also includes a number of useful text manipulation functions such as <tt>simple_format</tt>,
<tt>pluralize</tt>, <tt>word_wrap</tt>, and <tt>truncate</tt>.

simple_format("hello\nworld") # => "<p>hello<br/>world</p>"
pluralize(2, 'person') => '2 people'
word_wrap('Once upon a time', :line_width => 8) => "Once upon\na time"
truncate("Once upon a time in a world far far away", :length => 8) => "Once upon..."

These helpers can be invoked from any route or view within your application.

For a breakdown of all format helper methods, check out the
{padrino-helpers README}[http://github.com/padrino/padrino-framework/tree/master/padrino-helpers/].

=== Render Helpers

Render helpers are a series of helpers intended to make certain rendering template tasks easier to perform.
Expand Down
22 changes: 22 additions & 0 deletions padrino-helpers/README.rdoc
Expand Up @@ -389,8 +389,30 @@ passing javascript information from a js template to a javascript function.

There is also an alias for escape_html called <tt>h</tt> for even easier usage within templates.

Format helpers also includes a number of useful text manipulation functions such as <tt>simple_format</tt>,
<tt>pluralize</tt>, <tt>word_wrap</tt>, and <tt>truncate</tt>.

simple_format("hello\nworld") # => "<p>hello<br/>world</p>"
pluralize(2, 'person') => '2 people'
word_wrap('Once upon a time', :line_width => 8) => "Once upon\na time"
truncate("Once upon a time in a world far far away", :length => 8) => "Once upon..."

These helpers can be invoked from any route or view within your application.

The list of defined helpers in the 'format helpers' category:

* <tt>simple_format(text, html_options)</tt>
* Returns text transformed into HTML using simple formatting rules.
* <tt>simple_format("hello\nworld")</tt> => "<p>hello<br/>world</p>"
* <tt>pluralize(count, singular, plural = nil)</tt>
* Attempts to pluralize the singular word unless count is 1.
* <tt>pluralize(2, 'person')</tt> => '2 people'
* <tt>word_wrap(text, *args)</tt>
* Wraps the text into lines no longer than line_width width.
* <tt>word_wrap('Once upon a time', :line_width => 8)</tt> => "Once upon\na time"
* <tt>truncate(text, *args)</tt>
* Truncates a given text after a given :length if text is longer than :length (defaults to 30).
* <tt>truncate("Once upon a time in a world far far away", :length => 8)</tt> => "Once upon..."
* <tt>escape_html</tt> (alias <tt>h</tt> and <tt>h!</tt>)
* (from RackUtils) Escape ampersands, brackets and quotes to their HTML/XML entities.
* <tt>relative_time_ago(date)</tt>
Expand Down
48 changes: 48 additions & 0 deletions padrino-helpers/lib/padrino-helpers/format_helpers.rb
Expand Up @@ -16,6 +16,54 @@ def h!(text, blank_text = '&nbsp;')
h text
end

# Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines(\n\n) are considered
# as a paragraph and wrapped in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is appended.
# This method does not remove the newlines from the text.
# simple_format("hello\nworld") # => "<p>hello<br/>world</p>"
def simple_format(text, html_options={})
start_tag = tag('p', html_options.merge(:open => true))
text = text.to_s.dup
text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n
text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph
text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
text.insert 0, start_tag
text << "</p>"
end

# Attempts to pluralize the singular word unless count is 1. If plural is supplied, it will use that when count is > 1,
# otherwise it will use the Inflector to determine the plural form
# pluralize(2, 'person') => '2 people'
def pluralize(count, singular, plural = nil)
"#{count || 0} " + ((count == 1 || count == '1') ? singular : (plural || singular.pluralize))
end

# Truncates a given text after a given :length if text is longer than :length (defaults to 30).
# The last characters will be replaced with the :omission (defaults to "…") for a total length not exceeding :length.
# truncate("Once upon a time in a world far far away", :length => 8) => "Once upon..."
def truncate(text, *args)
options = args.extract_options!
options.reverse_merge!(:length => 30, :omission => "...")
if text
len = options[:length] - options[:omission].length
chars = text
(chars.length > options[:length] ? chars[0...len] + options[:omission] : text).to_s
end
end

# Wraps the text into lines no longer than line_width width.
# This method breaks on the first whitespace character that does not exceed line_width (which is 80 by default).
# word_wrap('Once upon a time', :line_width => 8) => "Once upon\na time"
def word_wrap(text, *args)
options = args.extract_options!
unless args.blank?
options[:line_width] = args[0] || 80
end
options.reverse_merge!(:line_width => 80)

text.split("\n").collect do |line|
line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line
end * "\n"
end

# Smart time helper which returns relative text representing times for recent dates
# and absolutes for dates that are far removed from the current date
Expand Down
62 changes: 62 additions & 0 deletions padrino-helpers/test/test_format_helpers.rb
Expand Up @@ -8,6 +8,68 @@ def app

include Padrino::Helpers::FormatHelpers

context 'for #simple_format method' do
should "format simple text into html format" do
actual_text = simple_format("Here is some basic text...\n...with a line break.")
assert_equal "<p>Here is some basic text...\n<br />...with a line break.</p>", actual_text
end

should "format more text into html format" do
actual_text = simple_format("We want to put a paragraph...\n\n...right there.")
assert_equal "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>", actual_text
end

should "support defining a class for the paragraphs" do
actual_text = simple_format("Look ma! A class!", :class => 'description')
assert_equal "<p class=\"description\">Look ma! A class!</p>", actual_text
end
end

context 'for #pluralize method' do
should "return singular count for 1 item collections" do
actual_text = pluralize(1, 'person')
assert_equal '1 person', actual_text
end
should "return plural count for empty collections" do
actual_text = pluralize(0, 'person')
assert_equal '0 people', actual_text
end
should "return plural count for many collections" do
actual_text = pluralize(2, 'person')
assert_equal '2 people', actual_text
end
should "return pluralized word specified as argument" do
actual_text = pluralize(3, 'person', 'users')
assert_equal '3 users', actual_text
end
end

context 'for #word_wrap method' do
should "return proper formatting for 8 max width" do
actual_text = word_wrap('Once upon a time', :line_width => 8)
assert_equal "Once\nupon a\ntime", actual_text
end
should "return proper formatting for 1 max width" do
actual_text = word_wrap('Once upon a time', :line_width => 1)
assert_equal "Once\nupon\na\ntime", actual_text
end
end

context 'for #truncate method' do
should "support default truncation" do
actual_text = truncate("Once upon a time in a world far far away")
assert_equal "Once upon a time in a world...", actual_text
end
should "support specifying length" do
actual_text = truncate("Once upon a time in a world far far away", :length => 14)
assert_equal "Once upon a...", actual_text
end
should "support specifying omission text" do
actual_text = truncate("And they found that many people were sleeping better.", :length => 25, :omission => "(clipped)")
assert_equal "And they found t(clipped)", actual_text
end
end

context 'for #h and #h! method' do
should "escape the simple html" do
assert_equal '&lt;h1&gt;hello&lt;/h1&gt;', h('<h1>hello</h1>')
Expand Down

0 comments on commit e37c21c

Please sign in to comment.