<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.2" -->
<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/"
	>

<channel>
	<title>Rails Garden</title>
	<link>http://www.railsgarden.com</link>
	<description>A delicious blend of Ruby and Rails...</description>
	<pubDate>Mon, 06 Apr 2009 05:05:46 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.2</generator>
	<language>en</language>
			<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 :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 - 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>
		</item>
		<item>
		<title>The Economics of Supporting IE6</title>
		<link>http://www.railsgarden.com/2009/01/03/the-economics-of-supporting-ie6/</link>
		<comments>http://www.railsgarden.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 - what&#8217;s the magic number?  Making decisions this way is rather naive - 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 - 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://www.railsgarden.com/2009/01/03/the-economics-of-supporting-ie6/feed/</wfw:commentRss>
		</item>
		<item>
		<title>ActiveRecord Drafts with has_draft</title>
		<link>http://www.railsgarden.com/2008/12/30/activerecord-drafts-with-has_draft/</link>
		<comments>http://www.railsgarden.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 [...]]]></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/railsgarden/has_draft/tree" 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://www.railsgarden.com/2008/12/30/activerecord-drafts-with-has_draft/feed/</wfw:commentRss>
		</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>:on</tt> - specifies one or many model names for which to check error messages.</li>
<li><tt>:model_error_type</tt> - specifies the message type to use for validation errors; defaults to ‘error’</li>
<li><tt>:flash_types</tt> - 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> - Specifies HTML options for the containing div</li>
<li><tt>:id</tt> - Specifies ID of the containing div; defaults to ‘message_block’</li>
<li><tt>:class</tt> - 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/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>
		</item>
		<item>
		<title>Inverting Permission-Based Filtering with named_scope</title>
		<link>http://www.railsgarden.com/2008/07/05/inverting-permission-based-filtering-with-named_scope/</link>
		<comments>http://www.railsgarden.com/2008/07/05/inverting-permission-based-filtering-with-named_scope/#comments</comments>
		<pubDate>Sat, 05 Jul 2008 14:22:26 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/07/05/inverting-permission-based-filtering-with-named_scope/</guid>
		<description><![CDATA[The addition of named_scope in Rails 2.1 has revealed several elegant approaches for modeling complex problem domains in ActiveRecord.  One I came across recently while working on an app with a somewhat complex permissions system was a permission-based filtering mechanism.  In this case I was dealing with permission for a given user to manage an [...]]]></description>
			<content:encoded><![CDATA[<p>The addition of named_scope in Rails 2.1 has revealed several elegant approaches for modeling complex problem domains in ActiveRecord.  One I came across recently while working on an app with a somewhat complex permissions system was a permission-based filtering mechanism.  In this case I was dealing with permission for a given user to manage an &#8220;office&#8221;, while a user could be at one of three permission &#8220;levels&#8221;, one of which has specific office assignments (or it&#8217;s assumed all are manageable if user.can_manage_all_offices is true).  Lot&#8217;s of necessary conditional logic there.</p>
<p>Now a normal approach to such a task to &#8220;show a list of offices that the user can manage&#8221; (for a drop-down for an interface perhaps) might be something like this:</p>
<pre class="rails" name="code">
# In controller:
if current_user.can_manage_company?
  @offices = Office.find(:all)
elsif current_user.office_access_level? &amp;&amp; current_user.can_manage_all_offices?
  @offices.find(:all)
elsif current_user.office_access_level?
  @offices.find(:all, :conditions =&gt; {:id =&gt; current_user.manageable_offices.map(&amp;:id) })
else
  @offices = []
end
</pre>
<p>But this approach starts at the user level and, using a lot of conditional logic baked right into places we don&#8217;t want, makes different calls to Office, which isn&#8217;t very DRY, and certainly not consistent with fat models skinny controllers.  So I considered inverting this approach and instead starting with an office, and asking it what &#8220;is manageable by&#8221; a given user.  Consider this alternative:</p>
<pre class="rails" name="code">
# In office.rb
named_scope :manageable_by, lambda {|user|
  case
  when user.can_manage_company? then {}
  when user.office_access_level? &amp;&amp; user.can_manage_all_offices? then {}
  when user.office_access_level? then {:conditions =&gt; {:id =&gt; user.manageable_offices.map(&amp;:id)}}
  else {:conditions =&gt; "1 = 0"}
  end
}

# Then in controller:
@offices = Office.manageable_by(current_user)
</pre>
<p>This seems much more elegant to me.  I&#8217;m in general finding a lot of opportunities for inverting the way I designed something without named_scope to be more model-centric, so this approach helps further the design principle of &#8220;fat models, skinny controllers&#8221;.  Sure you could do this before by defining your own methods and using with_scope, but named_scope just makes it all the more elegant.</p>
<p>Another advantage with using the named scope stuff is that you can chain scopes together.  Let&#8217;s say that in another controller I want to do the same thing but instead restrict results to active offices only.  I can create an &#8220;active&#8221; named scope that scopes :conditions =&gt; {:active =&gt; true}, then in the controller simply do this instead:</p>
<pre class="rails" name="code">
@offices = Office.manageable_by(current_user).active
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/07/05/inverting-permission-based-filtering-with-named_scope/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pleasing the JavaScript Download Time Whiners</title>
		<link>http://www.railsgarden.com/2008/06/28/pleasing-the-javascript-download-time-whiners/</link>
		<comments>http://www.railsgarden.com/2008/06/28/pleasing-the-javascript-download-time-whiners/#comments</comments>
		<pubDate>Sat, 28 Jun 2008 18:10:20 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/06/28/pleasing-the-javascript-download-time-whiners/</guid>
		<description><![CDATA[To me, the benefit of using JavaScript frameworks in an application cannot be overstated.  Though I&#8217;m also a fan of server-side frameworks, there is scarcely a reason not to use a client-side framework these days.  Of course the most common complaint against JavaScript frameworks is &#8220;bloat&#8221; and the long download time.  Funny that the most [...]]]></description>
			<content:encoded><![CDATA[<p>To me, the benefit of using JavaScript frameworks in an application cannot be overstated.  Though I&#8217;m also a fan of server-side frameworks, there is scarcely a reason not to use a client-side framework these days.  Of course the most common complaint against JavaScript frameworks is &#8220;bloat&#8221; and the long download time.  Funny that the most vocal of those complaining about the frameworks&#8217; download time are those who haven&#8217;t even ever used a framework to experience it&#8217;s benefits.  The tradeoff of course is a noticeable load hit for some users on slower connections vs. architectural elegance, much higher productivity, more maintainability, and less code in general.  To me in most cases the trade-off is a no-brainer in any sufficiently modern web application, but not to all.</p>
<p>Released recently is the <a href="http://code.google.com/apis/ajaxlibs/">Google Ajax Libraries API</a> which is basically a way of allowing browsers do download only one version of a given framework for all applications using that framework.  Currently most web applications host their own version of a given JavaScript library, which is inefficient across the spectrum of the internet since many sites are using the exact same library.  With Google Ajax Libraries you essentially reference Google&#8217;s hosted version of the library and the download hit is only incurred the first time a user visits any site using that framework.  So it&#8217;s quite likely that a user going to your site won&#8217;t have to download a thing - it&#8217;s as if the framework is at that point simply part of the user&#8217;s browser.</p>
<p>Of course this only works if it becomes widely used and I sure hope it will.  I&#8217;d encourange all developers to start using this in their production environments (development environments should still use local copies for local development:</p>
<p><a href="http://code.google.com/apis/ajaxlibs/">Google AJAX Libraries API</a><br />
<a href="http://agilewebdevelopment.com/plugins/google_ajax_libraries_api">Rails Plugin for Google AJAX Libraries API</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/06/28/pleasing-the-javascript-download-time-whiners/feed/</wfw:commentRss>
		</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>
		</item>
		<item>
		<title>Mac OS 10.5.3 Fixes Spaces</title>
		<link>http://www.railsgarden.com/2008/06/04/mac-os-1053-fixes-spaces/</link>
		<comments>http://www.railsgarden.com/2008/06/04/mac-os-1053-fixes-spaces/#comments</comments>
		<pubDate>Wed, 04 Jun 2008 19:25:21 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
		
		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/06/04/mac-os-1053-fixes-spaces/</guid>
		<description><![CDATA[Though I&#8217;ve been extremely happy with leopard (in fact, why I finally bought a Mac), little quirks with spaces were frustrating.  Specifically, spaces seems to have been designed for users who want to place a separate application in each space.  I use spaces in a task-oriented manner where each space typically has a Firefox window, [...]]]></description>
			<content:encoded><![CDATA[<p>Though I&#8217;ve been extremely happy with leopard (in fact, why I finally bought a Mac), little quirks with spaces were frustrating.  Specifically, spaces seems to have been designed for users who want to place a separate application in each space.  I use spaces in a task-oriented manner where each space typically has a Firefox window, tabbed terminal, and TextMate.  Command-Tabbing and others workflow situations were just quirky.  Also, a huge annoyance was going into the terminal, typing &#8220;mate .&#8221; and having it open up a new TextMate window in whatever space already had a TextMate window.</p>
<p>I&#8217;m very pleased to report that 10.5.3 solves all of these problems, with one new option in the spaces dialog called &#8220;When switching to an application, switch to a space with open windows for the application.&#8221;  In fact, you want to <strong>uncheck</strong> this option if you are working in a task-oriented manner like me.  There were also some bug fixes in 10.5.3 which transcend this new option.</p>
<p>With these frustrations gone I feel very solid working with 3-5 project workspaces at once and can move efficiently within and among them.</p>
<p>Upgrade to 10.5.3 now if you haven&#8217;t already done so!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/06/04/mac-os-1053-fixes-spaces/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Configuring Passenger (mod_rails) on SliceHost with Ubuntu 7.10</title>
		<link>http://www.railsgarden.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/</link>
		<comments>http://www.railsgarden.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 [...]]]></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 - 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 - Part 1</a><a href="http://articles.slicehost.com/2007/11/6/ubuntu-gutsy-setup-page-2">Ubuntu Setup - 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 - 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 - 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 - 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 - 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 - 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 - it could be a major step forward in the proliferation of Rails hosting.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/04/12/configurating-passenger-mod_rails-on-slicehost-with-ubuntu-710/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby on Rails is going down! Introducing: Cobol on Cogs:</title>
		<link>http://www.railsgarden.com/2008/04/01/ruby-on-rails-is-going-down-introducing-cobol-on-cogs/</link>
		<comments>http://www.railsgarden.com/2008/04/01/ruby-on-rails-is-going-down-introducing-cobol-on-cogs/#comments</comments>
		<pubDate>Tue, 01 Apr 2008 23:12:57 +0000</pubDate>
		<dc:creator>benhughes</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.railsgarden.com/2008/04/01/ruby-on-rails-is-going-down-introducing-cobol-on-cogs/</guid>
		<description><![CDATA[I am convinced this is the next big thing: Cobol on Cogs.  Definitely the future of web development.  As of today I renounce Ruby on Rails and all it stands for!
]]></description>
			<content:encoded><![CDATA[<p>I am convinced this is the next big thing: <a href="HTTP://WWW.COBOLONCOGS.ORG/INDEX.HTM">Cobol on Cogs</a>.  Definitely the future of web development.  As of today I renounce Ruby on Rails and all it stands for!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.railsgarden.com/2008/04/01/ruby-on-rails-is-going-down-introducing-cobol-on-cogs/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
