<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rails Garden &#187; Rails Techniques</title>
	<atom:link href="http://www.railsgarden.com/category/rails-techniques/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.railsgarden.com</link>
	<description>A delicious blend of Ruby and Rails...</description>
	<lastBuildDate>Mon, 06 Apr 2009 05:05:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Take Control of your Field Values with nilify_blanks</title>
		<link>http://www.railsgarden.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/</link>
		<comments>http://www.railsgarden.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 20:10:58 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Techniques]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/</guid>
		<description><![CDATA[If in your data schema most or all of your fields are NULLable (the Rails default in migrations), you may have run into the issue whereby sometimes your fields are blank and sometimes they are NULL, two distinct representations of a &#8220;no data&#8221; state.  This arises in Rails often because when you submit a form [...]]]></description>
			<content:encoded><![CDATA[<p>If in your data schema most or all of your fields are NULLable (the Rails default in migrations), you may have run into the issue whereby sometimes your fields are blank and sometimes they are NULL, two distinct representations of a &#8220;no data&#8221; state.  This arises in Rails often because when you submit a form and the user doesn&#8217;t fill in a value, the value sent to the database is an empty string, even if you may prefer the field to just remain NULL.</p>
<p>Enter <a href="http://github.com/railsgarden/nilify_blanks">nilify_blanks</a>, my solution to handling this problem generically in your models.  With nilify_blanks you can specify the fields you want &#8220;nilified&#8221; (or default to all content fields) upon save if the field is blank.  This allows you to regain some consistency in how you represent data in the database.   Use of the plugin is best-explained with some examples:</p>
<p><strong>Basic Examples</strong></p>
<pre name="code" class="rails">
  # Checks and converts all fields in the model
  class Post &lt; ActiveRecord::Base
    nilify_blanks
  end

  # Checks and converts only the title and author fields
  class Post &lt; ActiveRecord::Base
    nilify_blanks <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nly =&gt; [:author, :title]
  end

  # Checks and converts all fields except for title and author
  class Post &lt; ActiveRecord::Base
    nilify_blanks :except =&gt; [:author, :title]
  end</pre>
<p><strong>Specifying a Callback</strong><br />
Checking uses an ActiveRecord before_save filter by default, but you can specify a different filter with the :before option.  Any filter will work &#8211; just first remove the &#8220;before_&#8221; prefix from the name.</p>
<pre name="code" class="rails">
  class Post &lt; ActiveRecord::Base
    nilify_blanks :before =&gt; :create
  end

  class Post &lt; ActiveRecord::Before
    nilify_blanks :before =&gt; :validation_on_update
  end</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>message_block: a error_messages_for replacement for flash message and model error handling</title>
		<link>http://www.railsgarden.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/</link>
		<comments>http://www.railsgarden.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 22:54:25 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails Plugins]]></category>
		<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/</guid>
		<description><![CDATA[
One of the most common needs in any application I build is to have some abstract way of handling messages to end users.  Sometimes I&#8217;ll want to show a confirmation message or a warning.  Other times I&#8217;ll want to show a confirmation message but also show ActiveRecord validations.  While the error_messages_for helper in Rails works [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.railsgarden.com/wp-content/uploads/2009/01/message_block_example1.png" alt="Message Block Example" style="float: right; margin-left: 12px; margin-bottom: 10px" /></p>
<p>One of the most common needs in any application I build is to have some abstract way of handling messages to end users.  Sometimes I&#8217;ll want to show a confirmation message or a warning.  Other times I&#8217;ll want to show a confirmation message but also show ActiveRecord validations.  While the error_messages_for helper in Rails works fairly well for showing ActiveRecord validation issues, I wanted a unified approach to handling this and flash messaging with multiple flash types in one package.</p>
<p>I <a href="http://www.railsgarden.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/">blogged before</a> about an approach I developed to solve this problem, I <a href="http://github.com/railsgarden/message_block" title="message_block Rails Plugin">rolled my own message_block plugin</a>.  The README file explains things pretty so be sure to check it out for more details, but here is the intro:</p>
<p><strong>Introduction</strong>:</p>
<p>Implements the common view pattern by which a list of messages are shown at the top, often a combination of flash messages and ActiveRecord validation issues on one or more models. This allows for a nice, stylized block of messages at the top of the page with icons indicating what type of message it is (error, confirmation, warning, etc.)</p>
<p>This view helper acts as a replacement for error_messages_for by taking error messages from your models and combing them with flash messages (multiple types such as error, confirm, etc.) and outputting them to your view. This plugin comes with an example stylesheet and images.</p>
<p><strong>Usage</strong>:</p>
<p>Once you install this, you should now have a set of images at public/images/message_block and a basic stylesheet installed at public/stylesheets/message_block.css. First you’ll want to either reference this in your layout or copy the declarations to your main layout. Then you can use the helper <tt>&lt;%= message_block %&gt;</tt> as described below:</p>
<p>The first argument specifies a hash options:</p>
<ul>
<li><tt> <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n</tt> &#8211; specifies one or many model names for which to check error messages.</li>
<li><tt>:model_error_type</tt> &#8211; specifies the message type to use for validation errors; defaults to ‘error’</li>
<li><tt>:flash_types</tt> &#8211; specifies the keys to check in the flash hash. Messages will be grouped in ul lists according to this type. Defaults to: %w(back confirm error info warn)</li>
<li><tt>:html</tt> &#8211; Specifies HTML options for the containing div</li>
<li><tt>:id</tt> &#8211; Specifies ID of the containing div; defaults to ‘message_block’</li>
<li><tt>:class</tt> &#8211; Specifies class name of the containing div; defaults to nothing.</li>
</ul>
<p>Imagine you have a form for entering a user and a comment:</p>
<pre name="code" class="rails">
&lt;%= message_block <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; [:user, :comment] %&gt;</pre>
<p>Imagine also you set these flash variables in the controller:</p>
<pre name="code" class="rails">
  class CommentsController
    def create
      flash.now[:error] = "Error A"
      flash.now[:confirm] = "Confirmation A"  # Note you can use different types
      flash.now[:warn] = ["Warn A", "Warn B"]  # Can set to an array for multiple messages
    end
  end</pre>
<p>And let’s say that you want to show these messages but also show the validation issues given that both user and comment fail ActiveRecord validation:</p>
<pre name="code" class="html">
  &lt;div id="message_block"&gt;
    &lt;ul class="error"&gt;
      &lt;li&gt;Error A&lt;/li&gt;
      &lt;li&gt;User first name is required.&lt;/li&gt;
      &lt;li&gt;Comment contents is required.&lt;/li&gt;
    &lt;/ul&gt;
    &lt;ul class="confirm"&gt;
      &lt;li&gt;Confirmation A&lt;/li&gt;
    &lt;/ul&gt;
    &lt;ul class="warn"&gt;
      &lt;li&gt;Warn A&lt;/li&gt;
      &lt;li&gt;Warn B&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;</pre>
<p>Which will by default leave you with this look:</p>
<p><img src="http://www.railsgarden.com/wp-content/uploads/2009/01/message_block_example.png" alt="Message Block Example" /></p>
<p><a href="http://github.com/railsgarden/message_block" title="message_block on GitHub"><strong>message_block on GitHub</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>named_scope with acts_as_tree</title>
		<link>http://www.railsgarden.com/2008/06/25/named_scope-with-acts_as_tree/</link>
		<comments>http://www.railsgarden.com/2008/06/25/named_scope-with-acts_as_tree/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 16:40:08 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Techniques]]></category>
		<category><![CDATA[Rails Tools]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/06/25/named_scope-with-acts_as_tree/</guid>
		<description><![CDATA[I fairly often use the acts_as_tree plugin in my applications.  While acts_as_nested_set (and superior variants..) is more powerful, often times a simple two-level deep hierarchy is all I need and acts_as_tree is simple.  I&#8217;ve found the new named_scope functionality in Rails 2.1 to be very helpful when dealing with tree data structures.
Firstly, it&#8217;s somewhat rare [...]]]></description>
			<content:encoded><![CDATA[<p>I fairly often use the acts_as_tree plugin in my applications.  While acts_as_nested_set (and superior variants..) is more powerful, often times a simple two-level deep hierarchy is all I need and acts_as_tree is simple.  I&#8217;ve found the new named_scope functionality in Rails 2.1 to be very helpful when dealing with tree data structures.</p>
<p>Firstly, it&#8217;s somewhat rare that I have one single root node in the tree structure (which is apparently how it&#8217;s meant to be used).  Instead I&#8217;ll have multiple &#8220;parent&#8221; nodes designated with a NULL parent_id and children beneath.  In the past I&#8217;ve always done something like: find(:all, :conditions =&gt; {:parent_id =&gt; nil}) to grab the top entries.  Instead with nested set you can do this:</p>
<pre name="code" class="rails">
named_scope :top, :conditions =&gt; {:parent_id =&gt; nil}

#Then:
Category.top
</pre>
<p>Another common task when dealing with hierarchical categories is to query on the base object (products for example) for members that are &#8220;part of&#8221; that category.  Specifically, part of in a 2-level heirarchy simply means &#8220;where id = ? or parent_id = ?&#8221; on the joined categories table.  Because this involves a join it was somewhat clunky to do before.  Now with nested set, on the product model I can declare this:</p>
<pre name="code" class="rails">
named_scope :in_category, lambda {|c| {:include =&gt; [:category], :conditions =&gt; ["categories.id = ? OR categories.parent_id = ?", c, c]} }

# Then:
Product.in_category(3)
</pre>
<p>I would also highly encourage you all to check out <a href="http://railscasts.com/">RailsCasts</a> Episode 112 &#8220;Anonymous Scopes&#8221; by Ryan Bates where he outlines a pattern for handling conditions elegantly with searches using named_scopes in Rails 2.1, something I&#8217;ve always found to be lacking from Rails core and always resorted to using plugins like criteria_query.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/06/25/named_scope-with-acts_as_tree/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Nested URL Parameters</title>
		<link>http://www.railsgarden.com/2007/12/20/nested-url-parameters/</link>
		<comments>http://www.railsgarden.com/2007/12/20/nested-url-parameters/#comments</comments>
		<pubDate>Thu, 20 Dec 2007 15:07:12 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Plugins]]></category>
		<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2007/12/20/nested-url-parameters/</guid>
		<description><![CDATA[One of the great things about Rails is the ability to wire together form logic with extreme ease through Rails’ support of essentially representing hashes through the “object[name]” syntax of URL parameters. Arrays are also supported in a similar manner, making things like many-to-many relationship management cake.
In Rails 1.2 one issue I ran into is [...]]]></description>
			<content:encoded><![CDATA[<p>One of the great things about Rails is the ability to wire together form logic with extreme ease through Rails’ support of essentially representing hashes through the “object[name]” syntax of URL parameters. Arrays are also supported in a similar manner, making things like many-to-many relationship management cake.</p>
<p>In Rails 1.2 one issue I ran into is that this hash-based access logic cannot be nested when using helpers such as url_for (which is in turned used by helpers such as link_to, etc.) This type of functionality is rather useful when you are trying to encapsulate a set of name-value pairs within one “thing”, such as a “search” which is many criteria =&gt; value pairs. For a particularly project of mine I established a pretty nice design pattern for working with searches and results in a very abstract manner, an area of Rails that I generally find underdeveloped with no standard practice.</p>
<p>I was lucky to stumble on a Rails plugin that monkey-patches Rails to support this: nested_params_patch. Information about this plugin is quite sparse but this article does a good job of better-explaining what the plugin does. Essentially it allows you to do things like this:</p>
<pre name="code" class="rails">
person_url(:name =&gt; {0 =&gt; 'Ryan', 1 =&gt; 'Kinderman})
</pre>
<p>Pretty cool stuff! I am always amazed and the kind of plugins and extensions that are possible, all resulting from Ruby’s dynamicism and Rails’ heavily extensible architecture.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2007/12/20/nested-url-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>User Alert Management with flash and ActiveRecord::Errors</title>
		<link>http://www.railsgarden.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/</link>
		<comments>http://www.railsgarden.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/#comments</comments>
		<pubDate>Tue, 11 Dec 2007 15:01:56 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/</guid>
		<description><![CDATA[A very common paradigm in web application development is presenting the user with some sort of alert or flash message at the top of a page. These alerts are often styled with a background and some sort of icon to the left to indicate what type of error it is. Typically there are a few [...]]]></description>
			<content:encoded><![CDATA[<p>A very common paradigm in web application development is presenting the user with some sort of alert or flash message at the top of a page. These alerts are often styled with a background and some sort of icon to the left to indicate what type of error it is. Typically there are a few different types of messages such as “error”, “warning”, “confirmation”, etc., perhaps each type styled differently. Furthermore, such a block typically should support showing a set of messages within one type; not just one string. In Rails the two sources of these messages are usually either the flash object (such as flash[:error]) or ActiveRecord validations errors.</p>
<p>Here is an example of what I mean:</p>
<p>I’ve created a helper method that makes working with these types of messages a breeze.</p>
<p>Essentially it allows you to use the flash object with any of the following keys to specify messages: error, confirm, back, info, and warn (though you can modify it to suit any group of message types). You can either assign a string directly to this which is common, or create it as an array with multiple string messages. The helper will then read these flash objects and display it as a message block that can be styled with CSS, supporting multiple messages per type, separated by type, as well as dynamically grabbing ActiveRecord validation errors off of model object(s) of your choosing and showing those also. The usage of the helper method in your views is as follows</p>
<pre name="code" class="ruby">
# In Controller:
flash[:confirm] = "Thank you for your input."
flash[:error] = []
flash[:error] &lt;&lt; "Wrong Address"
flash[:error] &lt;&lt; "Wrong Name"

# In View:
&lt;%= message_block %&gt;

# Or if you want to display errors on @customer
# as well as the flash messages,
&lt;%= message_block <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; :customer %&gt;

# You can even have it watch multiple model
# objects for errors:
&lt;%= message_block <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; [:customer, <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder] %&gt;
Here is the helper method that makes this happen:

# Outputs the error messages block.
# The first argument specifies a hash options:
# * <img src='http://www.railsgarden.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; :products   Also includes AR validation errors for @products
# * :clear =&gt; true     Clears messages after displaying
# * :keep =&gt; true      Keeps around messages for next response cycle
#
def message_block(options = {})
  out = ""

  [:back, :confirm, :error, :info, :warn].each do |type|
    next if flash[type].nil? or flash[type].empty?
    flash[type] = [flash[type]] unless flash[type].is_a?(Array)

    out &lt;&lt; "&lt;div class=\"container #{type}\"&gt;&lt;ul&gt;\n"
    flash[type].each {|msg| out &lt;&lt; "&lt;li&gt;#{h(msg.to_s)}&lt;/li&gt;\n"}
    out &lt;&lt; "&lt;/ul&gt;&lt;/div&gt;\n"

    flash[type] = nil if options[:clear]
    flash.keep[type] if options[:keep]
  end

  if options[:on]
    options[:on] = [options[:on]] unless options[:on].kind_of?(Array)
    models = options[:on].map {|m| instance_variable_get("@" + m.to_s)}.select {|m| !m.nil?}
    errors = models.inject([]) {|b,m| b += m.errors.full_messages}

    if errors.size &gt; 0
      out &lt;&lt; "&lt;div class=\"container error\"&gt;&lt;ul&gt;\n"
      errors.each {|msg| out &lt;&lt; "&lt;li&gt;#{h(msg.to_s)}&lt;/li&gt;\n"}
      out &lt;&lt; "&lt;/ul&gt;&lt;/div&gt;\n"
    end
  end

  content_tag(:div, out, :id =&gt; 'message_block', :class =&gt; 'flash')
end
</pre>
<p>And the CSS code that works with it:</p>
<pre name="code" class="css">
/*** Flash Messages ***/
.flash {

}

.flash ul {
    padding-left: 0pt;
    margin-bottom: 0pt;
    list-style-type: none;
    margin-left: 0pt;
}

.flash ul li {
    background: transparent url(../images/icons/bullets/gt.gif) no-repeat scroll left center;
    margin-bottom: 0.6em;
    padding-left: 1em;
    vertical-align: top;
}

.flash .container {
    padding: 1em;
    padding-left: 5em;
    margin-bottom: 1.5em;
}

.flash .error {
    background: #fcf6d0 url(../images/icons/flashes/error.gif) 1.5em 1em no-repeat;
    border-top: 1px solid #ecd757;
    border-bottom: 1px solid #ecd757;
}
.flash .back {
    background: #e9f3dc url(../images/icons/flashes/back.gif) 1.5em 1em no-repeat;
    border-top: 1px solid #bfcbb0;
    border-bottom: 1px solid #bfcbb0;
}

.flash .confirm {
    background: #e9f3dc url(../images/icons/flashes/confirm.gif) 1.5em 1em no-repeat;
    border-top: 1px solid #bfcbb0;
    border-bottom: 1px solid #bfcbb0;
}

.flash .info {
    background: #dee9f4 url(../images/icons/flashes/info.gif) 1.5em 1em no-repeat;
    border-top: 1px solid #b4c5d5;
    border-bottom: 1px solid #b4c5d5;
}

.flash .warn {
    background: #fcf6d0 url(../images/icons/flashes/warn.gif) 1.5em 1em no-repeat;
    border-top: 1px solid #ecd757;
    border-bottom: 1px solid #ecd757;
}
</pre>
<p>You may even want to consider writing a before_filter in your application controller that sets the flash types to arrays so you can just add messages to them with the &lt;&lt; operator:</p>
<pre name="code" class="ruby">
class ApplicationController &lt; ActionController::Base
  before_filter :initialize_flash_types

  def initialize_flash_types
    [:back, :confirm, :error, :info, :warn].each {|type| flash[type] = []}
  end
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>HTML-Aware Truncate Text</title>
		<link>http://www.railsgarden.com/2007/12/09/html-aware-truncate-text/</link>
		<comments>http://www.railsgarden.com/2007/12/09/html-aware-truncate-text/#comments</comments>
		<pubDate>Sun, 09 Dec 2007 14:59:15 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2007/12/09/html-aware-truncate-text/</guid>
		<description><![CDATA[When building a large custom PHP CMS system for DigitalPeach, I ran into a very difficult issue: truncating text but maintaining HTML nested tags correctly. Specifically, we were looking to breaking up large articles composed using FCKEditor into separate pages after a certain character threshold. Once can easily see the problem:

&#60;p&#62;This is a test &#60;strong&#62;with [...]]]></description>
			<content:encoded><![CDATA[<p>When building a large custom PHP CMS system for DigitalPeach, I ran into a very difficult issue: truncating text but maintaining HTML nested tags correctly. Specifically, we were looking to breaking up large articles composed using FCKEditor into separate pages after a certain character threshold. Once can easily see the problem:</p>
<pre name="code" class="html">
&lt;p&gt;This is a test &lt;strong&gt;with some bold in here&lt;/strong&gt;.&lt;/p&gt;</pre>
<p>Now imaging having to truncate this text to 30 characters, and you end up with this:</p>
<pre name="code" class="html">
This is a test &lt;strong&gt;with</pre>
<p>While this example isn’t quite so severe and at worst would only make the rest of the text within the block-level element bold, clearly if we do a truncation that is blind to HTML some serious problems can arise. Furthermore, even if it doesn’t have much practical significance, you are breaking XHTML.</p>
<p>I was lucky to stumble across an excellent article by Mike Burns who describes a Ruby method using REXML’s pull parser that can accomplish this. His example extended the String class, so I modified it to work as a Rails helper all in one method:</p>
<pre name="code" class="ruby">
def truncate_html(input, len = 30, extension = "...")
  def attrs_to_s(attrs)
    return '' if attrs.empty?
    attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ')
  end

  p = REXML::Parsers::PullParser.new(input)
    tags = []
    new_len = len
    results = ''
    while p.has_next? &amp;&amp; new_len &gt; 0
      p_e = p.pull
      case p_e.event_type
    when :start_element
      tags.push p_e[0]
      results &lt;&lt; "&lt;#{tags.last} #{attrs_to_s(p_e[1])}&gt;"
    when :end_element
      results &lt;&lt; "&lt;/#{tags.pop}&gt;"
    when :text
      results &lt;&lt; p_e[0].first(new_len)
      new_len -= p_e[0].length
    else
      results &lt;&lt; "&lt;!-- #{p_e.inspect} --&gt;"
    end
  end

  tags.reverse.each do |tag|
    results &lt;&lt; "&lt;/#{tag}&gt;"
  end

  results.to_s + (input.length &gt; len ? extension : '')
end
</pre>
<p>Note that the nested method above is a completely valid use of Ruby, though not widely used.</p>
<p>And now look at what it can do:</p>
<pre name="code" class="ruby">
truncate_html("&lt;p&gt;Test &lt;strong&gt;bold&lt;/strong&gt; done.&lt;/p&gt;", 30)
# =&gt; "&lt;p&gt;Test &lt;strong&gt;bold&lt;/strong&gt;&lt;/p&gt;..."</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2007/12/09/html-aware-truncate-text/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
