<?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>Code Colossus &#187; Rails Techniques</title>
	<atom:link href="http://codecolossus.com/category/rails-techniques/feed/" rel="self" type="application/rss+xml" />
	<link>http://codecolossus.com</link>
	<description>Software Craftsmanship with Ruby</description>
	<lastBuildDate>Sun, 15 May 2011 17:08:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Using ActiveModel::Name to simplify URL generation</title>
		<link>http://codecolossus.com/2011/05/01/using-activemodelname-to-simplify-url-generation/</link>
		<comments>http://codecolossus.com/2011/05/01/using-activemodelname-to-simplify-url-generation/#comments</comments>
		<pubDate>Sun, 01 May 2011 23:37:13 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://codecolossus.com/?p=78</guid>
		<description><![CDATA[Most Rails developers are familiar with generating RESTful URLs polymorphically by simply passing an object to one of many helper methods that expects a URL, such as link_to and form_for: # In Routes resources :articles # In View: form_for @article do &#124;f&#124; This capability extends beyond just single objects, supporting nested routes and specific action [...]]]></description>
			<content:encoded><![CDATA[<p>Most Rails developers are familiar with generating RESTful URLs polymorphically by simply passing an object to one of many helper methods that expects a URL, such as link_to and form_for:</p>
<pre name="code" class="rails">
# In Routes
resources :articles

# In View:
form_for @article do |f|
</pre>
<p>This capability extends beyond just single objects, supporting nested routes and specific action targeting; for example:</p>
<pre name="code" class="rails">
# In Routes:
namespace :admin do
  resources :categories do
    resources :articles
  end
end

# In View
form_for [:admin, @category, @article] do |f|
</pre>
<h3>Problem</h3>
<p>One problem I&#8217;ve run into with some frequency, however, is using this polymorphic path approach when the class name of the ActiveRecord model does not quite correspond directly with the resource name. This occurs most frequently when you want a little more context in your model naming which may not be necessary in routes. For example, lets look a domain model with customers having many customer locations:</p>
<pre name="code" class="rails">
# Models:
class Customer < ActiveRecord::Base
  has_many :locations, :class_name => "CustomerLocation"
end

class CustomerLocation < ActiveRecord::Base
  belongs_to :customer
end

# Routes:
resources :customers do
  resources :locations
end
</pre>
<p>In the above example, the model name is "CustomerLocation", but the resource name as specified in the routes is just "locations", since the context of customers is already well-established from the nesting. The problem with this is when we try to use our regular polymorphic path solution:</p>
<pre name="code" class="rails">
form_for [@customer, @location]
# Tries to generate: customer_customer_location_path(@customer, @location)
</pre>
<p>Many people when running into this will just do away with using the clean polymorphic path solution entirely and instead provide the URL explicitly:</p>
<pre name="code" class="rails">
form_for @location, :url => customer_location_path(@customer, @location)
</pre>
<p>This of course works but isn't exactly ideal.</p>
<h3>Solution</h3>
<p>While it might look like it's using the class name to construct the url helper method name, it's in fact using "model_name" instead (which defaults to the class name). But, this can be overridden!</p>
<pre name="code" class="rails">
class CustomerLocation < ActiveRecord::Base
  def self.model_name
    ActiveModel::Name.new("Location")
  end
end
</pre>
<p>After this, the polymorphic path [@customer, @location] works as we would expect.</p>
<p>Another common situation where this technique becomes useful is if you are working extensively with namespaced models. This is tricky because the namespace ends up becoming part of the model name, which almost surely does not map to your resource hierarchy:</p>
<pre name="code" class="rails">
# Model:
class Core::Customer < Core::Base
end

# View:
form_for @customer
# Tries to generate: core_customer_path(@customer)
</pre>
<p>Overriding model_name will allow you to explicitly define "Customer" as the model name, despite it being namespaced within "Core". But we can do better than that - if you have a base model for your namespace (as I believe is always a good practice), just put this in the base model:</p>
<pre name="code" class="rails">
class Core::Base < ActiveRecord::Base
  def self.model_name
    ActiveModel::Name.new(name.split("::").last)
  end
end
</pre>
<p>Although this technique has served me well in many apps, do be aware that the model name is used in some other instances throughout Rails such as error_messages_for, so do use this with care.</p>
<p>Though all of the above examples are for ActiveModel/ActiveRecord 3.0 or higher, the same technique will work in Rails 2.3 by simply using "ActiveSupport::ModelName" in place of "ActiveModel::Name".</p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2011/05/01/using-activemodelname-to-simplify-url-generation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why you should always validate maximum lengths in models, and how to do so easily</title>
		<link>http://codecolossus.com/2011/01/01/why-you-should-always-validate-db-maximum-lengths-and-how-to-do-so-easily/</link>
		<comments>http://codecolossus.com/2011/01/01/why-you-should-always-validate-db-maximum-lengths-and-how-to-do-so-easily/#comments</comments>
		<pubDate>Sat, 01 Jan 2011 07:47:46 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails Plugins]]></category>
		<category><![CDATA[Rails Techniques]]></category>

		<guid isPermaLink="false">http://codecolossus.com/?p=69</guid>
		<description><![CDATA[Developers seem to rarely use validates_lengths_of with their models, despite there being an inherent maximum length on every string and text field &#8211; the one enforced by the database. Since table migrations in Rails set a fairly high maximum length for string attributes, most people don&#8217;t think twice about the possibly of that limit being [...]]]></description>
			<content:encoded><![CDATA[<p>Developers seem to rarely use validates_lengths_of with their models, despite there being an inherent maximum length on every string and text field &#8211; the one enforced by the database.  Since table migrations in Rails set a fairly high maximum length for string attributes, most people don&#8217;t think twice about the possibly of that limit being exhausted.  Even beyond this, there may be other reasons why the field limit is set fairly low, or perhaps you&#8217;re working with a legacy database.</p>
<p>Without validating maximum field lengths at the model level, ActiveRecord will still ship off the full field value as entered in an INSERT query.  From there two things might happen, and this depends on the database itself.<br />
1. It might fail the query with an ActiveRecord::StatementInvalid exception.  Since this is an exception most developers don&#8217;t routinely handle, this could cause the entire request to fail.  This occurs with SQL Server for sure, and possibly other databases.<br />
2. It might accept the query and simply truncate the result to the field limit.  This might sound better than #1, but IMO it&#8217;s actually worse: now you have an instance where the everything appeared to go along fine, but you might end up with <em>missing data</em>.  This is the default behavior with MySQL.</p>
<p>There&#8217;s another reason why you should always validate field lengths, and that&#8217;s to limit the possibilities for a Denial of Service attack.  If an attacker knows you aren&#8217;t validating field length and that whatever they&#8217;re providing is going straight into an SQL query and being sent to the database, they can craft extremely large requests that might fill up the pipe to the database.  Even if the data doesn&#8217;t actually end up being inserted in full, they&#8217;ve tied up a database connection and &#8211; since the regular old &#8220;mysql&#8221; gem will block for the query result &#8211; a Rails process.</p>
<p>Unfortunately in order to do this properly you essentially have to write validates_length_of lines (or the equivalent ActiveRecord 3 form) for each attribute, with it&#8217;s maximum database length.  To make this easy, I wrote a gem called <a href="https://github.com/rubiety/validates_lengths_from_database">validates_lengths_from_database</a> that will introspect your database string field maximum lengths and automatically defines length validations for you.</p>
<p>To install, just include the gem in your Gemfile (works with Rails 2.3 and Rails 3.0):</p>
<pre name="code" class="rails">
gem "validates_lengths_from_database"
</pre>
<p>Then in your model you can activate validations:</p>
<pre name="code" class="rails">
  class Post < ActiveRecord::Base
    validates_lengths_from_database
  end
</pre>
<p>It also supports filter-style :only and :except options: </p>
<pre name="code" class="rails">
  class Post < ActiveRecord::Base
    validates_lengths_from_database :only => [:title, :contents]
  end

  class Post < ActiveRecord::Base
    validates_lengths_from_database :except => [:other_field]
  end
</pre>
<p>Note that this cannot be done at a global level directly against ActiveRecord::Base, since the validates_length_from_database method requires the class to have a table name (with the ability to load the schema). </p>
<p>For more information or to view the source, check out the project on GitHub: <a href="https://github.com/rubiety/validates_lengths_from_database">validates_lengths_from_database</a></p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2011/01/01/why-you-should-always-validate-db-maximum-lengths-and-how-to-do-so-easily/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Take Control of your Field Values with nilify_blanks</title>
		<link>http://codecolossus.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/</link>
		<comments>http://codecolossus.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/rubiety/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 :only =&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://codecolossus.com/2009/01/07/take-control-of-your-field-values-with-nilify_blanks/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>message_block: a error_messages_for replacement for flash message and model error handling</title>
		<link>http://codecolossus.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/</link>
		<comments>http://codecolossus.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>:on</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 :on =&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/rubiety/message_block" title="message_block on GitHub"><strong>message_block on GitHub</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2008/11/26/message_block-a-error_messages_for-replacement-for-flash-message-and-model-error-handling/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>named_scope with acts_as_tree</title>
		<link>http://codecolossus.com/2008/06/25/named_scope-with-acts_as_tree/</link>
		<comments>http://codecolossus.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 [...]]]></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://codecolossus.com/2008/06/25/named_scope-with-acts_as_tree/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Nested URL Parameters</title>
		<link>http://codecolossus.com/2007/12/20/nested-url-parameters/</link>
		<comments>http://codecolossus.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 [...]]]></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://codecolossus.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://codecolossus.com/2007/12/11/user-alert-management-with-flash-and-activerecorderrors/</link>
		<comments>http://codecolossus.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 :on =&gt; :customer %&gt;

# You can even have it watch multiple model
# objects for errors:
&lt;%= message_block :on =&gt; [:customer, :order] %&gt;
Here is the helper method that makes this happen:

# Outputs the error messages block.
# The first argument specifies a hash options:
# * :on =&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://codecolossus.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://codecolossus.com/2007/12/09/html-aware-truncate-text/</link>
		<comments>http://codecolossus.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 [...]]]></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://codecolossus.com/2007/12/09/html-aware-truncate-text/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

