<?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 General</title>
	<atom:link href="http://codecolossus.com/category/rails-general/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>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>The Economics of Supporting IE6</title>
		<link>http://codecolossus.com/2009/01/03/the-economics-of-supporting-ie6/</link>
		<comments>http://codecolossus.com/2009/01/03/the-economics-of-supporting-ie6/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 21:05:47 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Economics]]></category>
		<category><![CDATA[Rails General]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2009/01/03/the-economics-of-supporting-ie6/</guid>
		<description><![CDATA[I recently had a frustrating discussion with a developer friend of mine concerning building web applications to support Internet Explorer 6 that highlighted a recurring theme of technology people misunderstanding business and economic decision-making.  In it I found myself trying to defend a deliberate decision in an application I develop not to support IE6.  His [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had a frustrating discussion with a developer friend of mine concerning building web applications to support Internet Explorer 6 that highlighted a recurring theme of technology people misunderstanding business and economic decision-making.  In it I found myself trying to defend a deliberate decision in an application I develop not to support IE6.  His take was that because so many internet users still use IE6, there&#8217;s just no reason why we should not build our applications to support the browser.</p>
<p>Now there&#8217;s no doubt that Internet Explorer 6 continues to have large penetration in the browser market.  But this fact alone resulting in a categorical dismissal of the deliberately not supporting IE6 misses some key pieces of economic reasoning that must be considered.</p>
<p>Before outlining the reasoning, let&#8217;s just accept the false assumption that browser usage numbers alone should dictate your decision regarding browser support.  If this is the case, what&#8217;s the breaking point?  At what percentage use do you decide not to support &#8211; what&#8217;s the magic number?  Making decisions this way is rather naive &#8211; any choice here is mostly arbitrary and bears to relevance to the trade-off of costs and benefits or the other considerations I outline in the rest of this post.  The core objective here is to balance the benefit of having more users access to your applications (or more correctly, the <em>marginal revenue derived from the additional customers using only IE6</em>, since it isn&#8217;t safe to assume that browser and revenue-per-customer are uncorrelated) against the anticipated cost of making your application IE6-compatible. As such, the relevant decision should carefully consider this trade off.  To help make this decision, there are considerations on both the cost and the benefit side:</p>
<p><strong>Considerations on the Benefit Side </strong></p>
<p>One thing that&#8217;s commonly done is to cite browser numbers as of today as if that&#8217;s the complete picture.  As a case in point look at Google Chrome: numbers for this browser are quite low but many developers are rushing to provide support for it because of <em>the future expectation of higher numbers</em>.   Basing your decision on current penetration numbers at a particular point in time would be like performing stock valuation with last fiscal years profit only.  Many companies that aren&#8217;t even profitable are worth magnitudes larger than established revenue-sustaining firms.  Therefore, when considering browser penetration, we really should be thinking not only about today&#8217;s numbers but also about anticipated numbers in the future, since presumably the application in development will last at least a year or two.  Put simply, trends matter.Another important point to consider is your target audience.</p>
<p>It doesn&#8217;t come as a surprise that browser choice does has some correlation with technical ability, so if your application targets hip, young internet users well-versed in other web 2.0 applications, you can bet that the percentage of that group using IE6 is significantly less than the percentage of older folks who barely check their e-mail and use an older machine.</p>
<p>Yet another important consideration, particularly if you are working on an internal project, is what degree of control you have over your users&#8217; web browser.  For example, if you are working on an internal application used within your company, and the corporate standard is to use Firefox, then you aren&#8217;t going ot have much of a problem with IE6.   Even some applications, especially at first, are introduced to a smaller set of users with whom you may actually speak to in person and be able to influence the browser used with the application.  This is the case in one of the applications I work on and hence we haven&#8217;t found it worth it to support IE6 yet.</p>
<p><strong>Considerations on the Cost Side</strong></p>
<p>Implementing support for IE6 is not free.  Every web developer on Earth has a profound hate for Internet Explorer 6 with all it&#8217;s quirks, bugs, and non-compliance with established standards.  Creating semantic HTML/CSS markup that works well in IE6 is hard enough, but writing working JavaScript is five times more difficult to create and twenty times more difficult to debug.  Even when it&#8217;s working, often times you&#8217;ll have implemented hacks and other code smell that detracts from quality of the codebase.  Doing all this of course <em>costs money</em> since ultimately you are paying developers to produce the code and debug it for IE6.  In many cases this can be a significant additional expense.</p>
<p>Most importantly, the magnitude of this additional expense is extremely dependent on the specifics of the application.  A basic brochure ware website with no JavaScript would cost significantly less to support than a rich, web 2.0 application with significant interactivity.</p>
<p>Although it&#8217;s very difficult to quantify this cost (at least, more difficult than quantifying labor cost), there&#8217;s also something to be said for reducing code quality and structure for the sake of supporting IE6.  Extra DIVs, CSS hacks, less straightforward CSS due to lack of newer CSS selectors, and conditional statements in JavaScript all have a &#8220;cost&#8221; in a most abstract sense to the elegance of your codebase and may have additional maintenance costs in the future as you try to maintain a less clean codebase.</p>
<p>Another misunderstanding in general when thinking about costs and decision-making at the margin is that saving $1,000 in developer pay may not be the &#8220;real&#8221; economic cost here since keeping $1,000 cash may not be (and most certainly is not)<em> your next best alternative, </em>a concent economists call &#8220;opportunity cost&#8221;, which is the real cost that you should consider when making decisions.   Now in a more traditional setting your opportunity cost isn&#8217;t much higher than your cash expenditure so substituting cash isn&#8217;t a bad approach, but in a face-paced startup that&#8217;s growing very quickly, often times your opportunity cost can be enormous as new features and development have tremendous value.  Saving $1,000 in labor can be substantial if that $1,000 in capital could otherwise be used towards implementing new features that you  value at much, much more than $1,000.</p>
<p>The point here is not whether or not it makes sense for my particular application to support IE6.  Certainly it makes sense for many sites, usually content sites and those sites not targetted to a younger crowd, to support IE6 in full.  My point here is that decisions like these should not be shallowly-reasoned or be subject to categorical dismissals.  In decisions like this, it pays to approach a decision analytically like an economist would &#8211; think carefully about the costs and benefits.  And choosing which browsers your application supports is pretty trivial compared to all the other kinds of decisions in developing software that would benefit greatly from an application of economic reasoning.</p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2009/01/03/the-economics-of-supporting-ie6/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>ActiveRecord Drafts with has_draft</title>
		<link>http://codecolossus.com/2008/12/30/activerecord-drafts-with-has_draft/</link>
		<comments>http://codecolossus.com/2008/12/30/activerecord-drafts-with-has_draft/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 22:28:21 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Plugins]]></category>
		<category><![CDATA[Rails Tools]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/12/30/activerecord-drafts-with-has_draft/</guid>
		<description><![CDATA[I ran into a problem a while back of creating draft copies of ActiveRecord models for the purpose of establishing a draft/live system. I&#8217;ve since found a reason to resurrect this and publish it to GitHub and clean some things up. Check out has_draft on GitHub. has_draft allows for multiple &#8220;drafts&#8221; of a model which [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into a problem a while back of creating draft copies of ActiveRecord models for the purpose of establishing a draft/live system.  I&#8217;ve since found a reason to resurrect this and publish it to GitHub and clean some things up.  Check out <a href="https://github.com/rubiety/has_draft" title="has_draft">has_draft on GitHub</a>.</p>
<p>has_draft allows for multiple &#8220;drafts&#8221; of a model which can be useful when developing:</p>
<ul>
<li>Draft/Live Version of Pages, for examples</li>
<li>A workflow system whereby a live copy may need to be active while a draft copy is awaiting approval.</li>
</ul>
<p>The semantics of this as well as most of the inspiration comes from version_fu, an excellent plugin for a similar purpose of maintaining several &#8220;versions&#8221; of a model.</p>
<p>This was built to be able to be tacked on to existing models, so the data schema doesn&#8217;t need to change at all for the model this is applied to.  As such, drafts are actually stored in a nearly-identical table and there is a has_one relationship to this.  This separation allows the base model to really be treated just as before without having to apply conditions in queries to make sure you are really getting the &#8220;live&#8221; (non-draft) copy: Page.all will still only return the non-draft pages.  This separate table is backed by a model created on the fly as a constant on the original model class.  For example if a Page has_draft, a Page::Draft class will exist as the model for the page_drafts table.</p>
<p><strong>Basic Example:</strong>:</p>
<pre class="rails" name="code">
## First Migration (If Creating base model and drafts at the same time):
class InitialSchema &lt; ActiveRecord::Migration

  [:articles, :article_drafts].each do |table_name|
    create_table table_name, :force =&gt; true do |t|
      t.references :article if table_name == :article_drafts

      t.string :title
      t.text :summary
      t.text :body
      t.date :post_date
    end
  end
end

## Model Class
class Article &lt; ActiveRecord::Base
  has_draft
end

## Exposed Class Methods &amp; Scopes:
Article.draft_class
=&gt; Article::Draft
Article.with_draft.all
=&gt; (Articles that have an associated draft)
Article.without_draft.all
=&gt; (Articles with no associated draft)

## Usage Examples:
article = Article.create(
  :title =&gt; "My Title",
  :summary =&gt; "Information here.",
  :body =&gt; "Full body",
  :post_date =&gt; Date.today
)

article.has_draft?
=&gt; false

article.instantiate_draft!

article.has_draft?
=&gt; true

article.draft
=&gt; Article::Draft Instance

article.draft.update_attributes(
  :title =&gt; "New Title"
)

article.replace_with_draft!

article.title
=&gt; "New Title"

article.destroy_draft!

article.has_draft?
=&gt; false</pre>
<p><strong>Custom Options:</strong>:</p>
<pre class="rails" name="code">
## First Migration (If Creating base model and drafts at the same time):
class InitialSchema &lt; ActiveRecord::Migration

  [:articles, :article_copies].each do |table_name|
    create_table table_name, :force =&gt; true do |t|
      t.integer :news_article_id if table_name == :article_copies

      t.string :title
      t.text :summary
      t.text :body
      t.date :post_date
    end
  end

end

## Model Class
class Article &lt; ActiveRecord::Base
  has_draft :class_name =&gt; 'Copy', :foreign_key =&gt; :news_article_id, :table_name =&gt; 'article_copies'
end</pre>
<p><strong>Method Callbacks</strong>:<br />
There are three callbacks you can specify directly as methods.</p>
<pre class="rails" name="code">
class Article &lt; ActiveRecord::Base
  has_draft

  def before_instantiate_draft
    # Do Something
  end

  def before_replace_with_draft
    # Do Something
  end

  def before_destroy_draft
    # Do Something
  end
end</pre>
<p><strong>Block of Code Run for Draft Class</strong>:<br />
Because you don&#8217;t directly define the draft class, you can specify a block of code to be run in its<br />
context by passing a block to has_draft.</p>
<pre class="rails" name="code">
class Article &lt; ActiveRecord::Base
  belongs_to :user

  has_draft do
    belongs_to :last_updated_user

    def approve!
      self.approved_at = Time.now
      self.save
    end
  end

end</pre>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2008/12/30/activerecord-drafts-with-has_draft/feed/</wfw:commentRss>
		<slash:comments>3</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>Configuring Passenger (mod_rails) on SliceHost with Ubuntu 7.10</title>
		<link>http://codecolossus.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/</link>
		<comments>http://codecolossus.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/#comments</comments>
		<pubDate>Sat, 12 Apr 2008 19:30:34 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>
		<category><![CDATA[Rails Tools]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/</guid>
		<description><![CDATA[I had an opportunity to play around with Phusion Passenger (mod_rails) which was just released yesterday. Before yesterday all that was available was an introductory video showing Passenger being configured, and I was quite impressed by it&#8217;s ease. Clearly one of the problems with Rails as a major platform right now is it&#8217;s hosting situation. [...]]]></description>
			<content:encoded><![CDATA[<p>I had an opportunity to play around with <a href="http://www.modrails.com/">Phusion Passenger (mod_rails)</a> which was just released yesterday.  Before yesterday all that was available was an introductory video showing Passenger being configured, and I was quite impressed by it&#8217;s ease.  Clearly one of the problems with Rails as a major platform right now is it&#8217;s hosting situation.  Currently the best solution is to proxy HTTP requests from Apache or Nginx to a cluster of mongrels, which is tricky to set up and somewhat tedious &#8211; certainly not as as easy as a mod_php in Apache where things &#8220;just work&#8221;.  Phusion set out to overcome this problem and release a module for Apache that hosts Rails applications easily.  Here is what took me from a clean Ubuntu 7.10 slice from SliceHost to a working server with Passenger:<strong>Starting Out</strong>To start out, I used the following *excellent* SliceHost articles to get some of the basic packages installed such as Ruby and MySQL:<a href="http://articles.slicehost.com/2007/11/6/ubuntu-gutsy-setup-page-1">Ubuntu Setup &#8211; Part 1</a><a href="http://articles.slicehost.com/2007/11/6/ubuntu-gutsy-setup-page-2">Ubuntu Setup &#8211; Part 2</a><a href="http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-mysql-and-ror">MySQL and Rails</a><a href="http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-installing-apache-and-php5">Apache and PHP</a><a href="http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-apache-virtual-hosts">Apache Virtual Hosts</a><a href="http://articles.slicehost.com/2007/9/18/apache-virtual-hosts-permissions">Virtual Hosts &amp; Permissions</a>Note my permissions gotcha below &#8211; you may not want to strictly follow their permissions advice (where the global does not have read permission).I also installed sqlite3 as this is now the default database package used in Rails 2.0:
<pre class="ruby:nogutter:nocontrols" name="code">$ sudo aptitude install sqlite3$ sudo gem install sqlite3-ruby</pre>
<p><strong>Installing the Passenger Apache Module</strong>Using the simple <a href="http://www.modrails.com/install.html">instructions</a> on the Passenger website, I ran:
<pre class="ruby:nogutter:nocontrols" name="code">$ sudo gem install passenger$ passenger-install-apache2-module</pre>
<p>The passenger-install-apache2-module binary walks you through the installation of the Passenger.  On the first run, it told me I didn&#8217;t have some software that was required:
<pre class="ruby:nogutter:nocontrols" name="code">* GNU C++ compiler... found* Ruby development headers... found* OpenSSL support for Ruby... found* RubyGems... found* Rake... found at /usr/bin/rake* Apache 2... found at /usr/sbin/apache2* Apache 2 development headers... not found* Apache Portable Runtime (APR) development headers... not found* fastthread... foundSome required software is not installed.But don't worry, this installer will tell you how to install them....* To install Apache 2 development headers:Please run apt-get install apache2-prefork-dev as root.* To install Apache Portable Runtime (APR) development headers:Please run apt-get install libapr1-dev as root.</pre>
<p>Clearly the installer detected I was running Debian-based Linux and told me exactly what to do.  No compile errors or nasty dependency issues, just simple and clear instructions.  After installing the requisite software the installer compiled the Apache module and spit out this:
<pre class="ruby:nogutter:nocontrols" name="code">The Apache 2 module was successfully installed.Please edit your Apache configuration file, and add these lines:LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-1.0.1/ext/apache2/mod_passenger.soRailsSpawnServer /usr/lib/ruby/gems/1.8/gems/passenger-1.0.1/bin/passenger-spawn-serverRailsRuby /usr/bin/ruby1.8After you restart Apache, you are ready to deploy any numberof Ruby on Rails applications on Apache, without any furtherRuby on Rails-specific configuration!</pre>
<p>Note that it didn&#8217;t find or attempt to find where apache modules are installed as the actual compiled modules is kept within the Ruby gems directory, it just told me what lines to include in my Apache configuration file.  The last part of the installation says:
<pre class="ruby:nogutter:nocontrols" name="code">Deploying a Ruby on Rails application: an example.Suppose you have a Ruby on Rails application in /somewhere.Add a virtual host to your Apache configuration file,and set its DocumentRoot to /somewhere/public, like this:&lt;VirtualHost&gt;      ServerName www.yourhost.com      DocumentRoot /somewhere/public&lt;/VirtualHost&gt;And that's it!</pre>
<p>Now this is pretty cool&#8230; Passenger doesn&#8217;t even require virtual hosts to configure themselves as Rails applications.  It will automatically detect a Rails application (I&#8217;m unsure of the actual criteria here) based on the DocumentRoot that you provide.So I added the necessary lines specified above to /etc/apache2/apache2.conf to load the module.  Note that some deployments of Apache have their own way of managing modules; in Ubuntu there is a mods-available directory with individual configuration files for each module.  You could split up the above commands to follow the convention for your system of choice, but for my purposes I just dumped the three lines into apache2.conf.Then I created a new Rails application and pointed DocumentRoot to the Rails public directory.  Restart apache, and the site should then immediately work with no further configuration.<strong>Permissions Gotcha &#8211; Important!</strong>If you get:
<pre class="ruby:nogutter:nocontrols" name="code">RAILS_ROOT is not a directory.</pre>
<p>The first time I got to this point I was running into an extremely obscure problem &#8211; Rails was reporting that RAILS_ROOT wasn&#8217;t a directory.  After some debugging which involved hacking up the gem source code of both Rails and Passenger, I realized it was a permissions issue (what do you know). Passenger reports that it will run your Rails application as whatever user owns environment.rb.  However, it will set the effective group to that user&#8217;s primary UNIX group, NOT the group that environment.rb is owned by.  In my case, I set the group of all of the web files to www-data and no read or execute permissions whatsoever for other.  I figured this would be sufficient since Apache runs as www-data.  But in my case when Passenger got spawned, it got spawned running as bhughes:bhughes NOT bhughes:www-data, so it effectively couldn&#8217;t find the RAILS_ROOT directory and didn&#8217;t think it existed.  You can design your permissions scheme however you want, but make sure you keep this in mind.  I have an <a href="http://code.google.com/p/phusion-passenger/issues/detail?id=13">enhancement in Passenger&#8217;s ticketing system</a> for fixing this and allowing you to manually set the effective group (you already can explicitly set the effective user through the RailsUser option).<strong>More Passenger Configuration</strong>The Passenger <a href="http://www.modrails.com/documentation/Users%20guide.html">User&#8217;s Guide</a> is pretty good and includes some more specific configuration options you can choose, but the default appears to work fine.  The Rails environment is by default set to &#8220;production&#8221; though this can be changed (sadly, only server-wide, not on a virtual-host basis &#8211; but there is an enhancement in the issue tracker for this feature).<strong>Restarting Your App</strong>Restarting a Rails app hosted by Passenger is easy &#8211; simply touch a file called tmp/restart.txt within the Rails application root:
<pre class="ruby:nogutter:nocontrols" name="code">$ touch tmp/restart.txt</pre>
<p><strong>Capistrano</strong>Brian Ketelsen pointed out this Capistrano configuration which uses the touch tmp/restart.txt approach to restart and removes the .htaccess file which can cause issues:
<pre class="ruby" name="code">namespace :deploy do  task :start, :roles =&gt; :app do  end  task :stop, :roles =&gt; :app do  end  task :restart, :roles =&gt; :app do    run "touch #{release_path}/tmp/restart.txt"  end  task :after_update_code, :roles =&gt; :app do    run "rm -rf #{release_path}/public/.htaccess"  endend</pre>
<p><strong>Diagnosing Problems</strong>One of the absolutely wonderful things about Passenger is that problem diagnostics (regarding starting your Rails app) is fairly easy because Passenger includes its own nice error pages:<a href="http://izumi.plan99.net/blog/wp-content/uploads/2008/03/database_error.html">Database Error Example</a><a href="http://izumi.plan99.net/blog/wp-content/uploads/2008/03/framework_init_error.html">Framework Initialization Example</a><strong>Memory Management</strong>One of the issues with mongrel or thin is that they are constantly running and sucking up memory, even for sites that get very little traffic.  This leads to a situation where hosting very low-traffic sites is very inefficient from a system resources perspective.  This isn&#8217;t the case with PHP where memory usage spikes during traffic but is otherwise unused, allowing multiple sites to leverage the on and offs and maintain a pretty efficient hosting platform as far as memory is concerned.  One of the great feature of Passenger is that you can configure it to automatically shut down your Rails application if it is idle for a certain period of time.  Doing this obviously exerts a cost then on the next hit, but this may be an acceptable tradeoff for a server hosting many low-traffic sites.  The configuration option is RailsPoolIdleTime and there is more information on this in the user guide.<strong>Conclusion</strong>Obviously my introduction here doesn&#8217;t go in-depth into performance and ability of Passenger to scale.  Time will tell as people begin using this whether it is a viable solution for Rails hosting, but for me installing this and getting it to work was dirt simple, at least compared to the mod_proxy_balancer setup with mongrel clusters I have used in the past.  I&#8217;m not quite ready to actually host my sites using this but I&#8217;ll definitely be keeping my eye on this &#8211; it could be a major step forward in the proliferation of Rails hosting.</p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Book Review: Advanced Rails Recipes</title>
		<link>http://codecolossus.com/2008/01/06/book-review-advanced-rails-recipes/</link>
		<comments>http://codecolossus.com/2008/01/06/book-review-advanced-rails-recipes/#comments</comments>
		<pubDate>Sun, 06 Jan 2008 15:08:11 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Book Reviews]]></category>
		<category><![CDATA[Rails General]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/01/06/book-review-advanced-rails-recipes/</guid>
		<description><![CDATA[I’ve owned the original “Rails Recipes” book by Chad Fowler for a while now and it’s packed full of interesting information, but little of it I would consider “advanced”. When I heard a new book by The Pragmatic Programmers called “Advanced Rails Recipes”, meant to be similar in form to the previous book but explaining [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve owned the original “Rails Recipes” book by Chad Fowler for a while now and it’s packed full of interesting information, but little of it I would consider “advanced”. When I heard a new book by The Pragmatic Programmers called “Advanced Rails Recipes”, meant to be similar in form to the previous book but explaining more advanced techniques, I was very interested. Unfortunately it seems the publish date of this book has been pushed back a few times and it is now mid-March. Luckily it is available in beta PDF form online so last night I took the plunge and decided to buy it. It’s quick to read through and several of the recipes I skipped over because I wasn’t particularly interested, but suffice it to say that there is a lot of good stuff in this book. Some of the content isn’t very original, but some recipes really exceeded my expectations in originality and usefulness.</p>
<p>I won’t give an outline of the book since that’s available online, but let me point out a few very interesting recipes:</p>
<ul>
<li>Using IRB_RC to define useful shortcuts for yourself when navigating around your application with script/console.</li>
<li>Efficiently storing model-backed data in constants using class-level ActiveRecord find’s. Example: load all of your states into an Array when the application starts rather than loading them each time a form is displayed that needs to use them.</li>
<li>Capistrano multi-environment deployments which allow you to do things like “cap staging deploy” and “cap production deploy”. I’ve been doing this for a while with capistrano-ext but really capistrano-ext isn’t even needed. Every developer using capistrano should be making use of this and a staging environment.</li>
<li>Keeping database.yml and other files out of Subversion using a Capistrano after filter when deploying apps.</li>
<li>Keeping certain data outside the multiple-release capistrano paradigm by symbolic linking folders within public to subdirectories in shared. This is perfect for establishing a place to upload via FTP without requiring someone to go through the SVN commit and capistrano deploy route. I’ve also used this before but the mechanism described in the book is more elegant.</li>
<li>SQL query tracing – finding out where queries are being run and what is going on behind the scenes. Could come in useful when debugging a nasty situation.</li>
<li>Using a master/slave database configuration for large applications with Rick Olsen’s masochism plugin.</li>
<li>My favorite: Handling complex forms spanning multiple models each with possible one-to-many or many-to-many relationships using the “presenter” pattern. Essentially this allows you to have a layer of design abstraction between the controller and the models whereby you can design a “presenter” which acts as as “manager” of multiple model objects meant to be displayed using the same form. Difficult to explain in full here (buy the book!) but this sounds like a very elegant solution for more data-complex applications. I may do some refactoring with Rarenewspapers.com’s back-end to use this pattern.</li>
</ul>
<p>The book is still in beta form and there are definitely errors. Hopefully some more recipes will also be added (I’m hungry for more!) before the book is released, but ultimately the knowledge presented in Advanced Rails recipes will be very insightful for professional Rails developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2008/01/06/book-review-advanced-rails-recipes/feed/</wfw:commentRss>
		<slash:comments>0</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>Don&#8217;t use symbols for route parameters!</title>
		<link>http://codecolossus.com/2007/12/10/dont-use-symbols-for-route-parameters/</link>
		<comments>http://codecolossus.com/2007/12/10/dont-use-symbols-for-route-parameters/#comments</comments>
		<pubDate>Mon, 10 Dec 2007 15:04:04 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
				<category><![CDATA[Rails General]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2007/12/10/dont-use-symbols-for-route-parameters/</guid>
		<description><![CDATA[I&#8217;ve ran into this issue more than once: Be sure that you are using strings and not symbols when specifying parameters for routes. Particularly, if you specify a symbol for :action, Rails will fail to see your controller action yet still show your Rails view! This can sometimes be very difficult to diagnose. So, don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve ran into this issue more than once: Be sure that you are using strings and not symbols when specifying parameters for routes. Particularly, if you specify a symbol for :action, Rails will fail to see your controller action yet still show your Rails view! This can sometimes be very difficult to diagnose. So, don&#8217;t do this:</p>
<pre name="code" class="rails">
map.connect '/pages/:slug',
:controller =&gt; 'pages',
:action =&gt; :show
</pre>
<p>Do this:</p>
<pre name="code" class="rails">
map.connect '/pages/:slug',
:controller =&gt; 'pages',
:action =&gt; 'show'
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codecolossus.com/2007/12/10/dont-use-symbols-for-route-parameters/feed/</wfw:commentRss>
		<slash:comments>0</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>

