Skip to content
rails helper that works just like truncate, but it respects, and produces well formed html
Ruby
Latest commit 03892b0 Mar 17, 2011 @ianwhite Use nokogiri
Failed to load latest commit information.
lib Use nokogiri Mar 17, 2011
spec
.gitignore Changing to use all rake for build Feb 15, 2009
History.txt Changing to use all rake for build Feb 15, 2009
License.txt Changing to use all rake for build Feb 15, 2009
README.rdoc Use nokogiri Mar 17, 2011
Rakefile
Todo.txt Update Todo.txt Feb 27, 2009
garlic.rb Adde rails 2.3 branch to garlic build Apr 7, 2009
init.rb Changing to use all rake for build Feb 15, 2009

README.rdoc

ianwhite / truncate_html >info >api

TruncateHtml is just like the vanilla truncate rails helper, except it respects tags and html entities, and returns valid html.

Rexml and HtmlEntities are used for the parsing. If the input is invalid html, then nokogiri is used to fix it up (but is not used when the input is fine). If the input cannot be fixed up, then a TruncateHtmlHelper::InvalidHtml runtime error is raised.

Inspired and heavily influenced by this article by Mike Burns and the links contained therein.

Usage

when post.title is

<p>This is <em>my <strong>first</strong> post</em></p>

Then

<%= truncate_html post.title, :length => 15 %>

results in

<p>This is <em>my <strong>fir&hellip;</strong></em></p>

Dependencies

Requires the htmlentities and nokogiri gems:

in Gemfile:

gem "nokogiri"
gem "htmlentities"

in your environment.rb file (~ rails 2)

config.gem "nokogiri"
config.gem "htmlentities"

If you are on rails < 2.1, you need to explicitly include the following in your environment

require 'htmlentities'
require 'nokogiri'

Specs and Coverage

  • Coverage is 100% (C0)

  • CI: tested against all 2.x branches of rails

RSpec is used for testing, so the tests are in spec/ rather than test/ Do rake –tasks for more details.

garlic is used for CI. To see what versions are tested against see garlic.rb

Something went wrong with that request. Please try again.