<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><!-- generator="wordpress/2.3.1" --><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Ruby Saved My Life</title>
	<link>http://www.rubysavedmylife.com</link>
	<description />
	<pubDate>Thu, 24 Jan 2008 18:02:30 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/RubySavedMyLife" type="application/rss+xml" /><item>
		<title>Choosing Which Version of a Gem to Run</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/222441453/</link>
		<comments>http://www.rubysavedmylife.com/2008/01/24/choosing-which-version-of-a-gem-to-run/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 18:02:30 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Gem]]></category>

		<category><![CDATA[Tips]]></category>

		<category><![CDATA[versions]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2008/01/24/choosing-which-version-of-a-gem-to-run/</guid>
		<description><![CDATA[Paul Sturgess posted a nice little tip on how to How to use Capistrano 1.x to deploy Ruby on Rails apps when you have Cap 2.x.  Basically, the following syntax will allow you to choose which version of a gem to run:
cap _1.4.1_ deploy
Or say you want to generate a 1.2.3 rails app:
rails _1.2.3_ [...]]]></description>
			<content:encoded><![CDATA[<p>Paul Sturgess posted a nice little tip on how to <a href="http://www.paulsturgess.co.uk/articles/show/58-how-to-use-capistrano-1x-to-deploy-ruby-on-rails-apps-when-you-have-cap-2x#leave_comment" onclick="javascript:urchinTracker('/outbound/article/www.paulsturgess.co.uk');">How to use Capistrano 1.x to deploy Ruby on Rails apps when you have Cap 2.x</a>.  Basically, the following syntax will allow you to choose which version of a gem to run:</p>
<p><code>cap _1.4.1_ deploy</code></p>
<p>Or say you want to generate a 1.2.3 rails app:</p>
<p><code>rails _1.2.3_ my_old_app</code></p>
<p>Nice one Paul!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2008/01/24/choosing-which-version-of-a-gem-to-run/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2008/01/24/choosing-which-version-of-a-gem-to-run/</feedburner:origLink></item>
		<item>
		<title>jQuery: Embedding Behavior</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/216814316/</link>
		<comments>http://www.rubysavedmylife.com/2008/01/14/jquery-embedding-behavior/#comments</comments>
		<pubDate>Tue, 15 Jan 2008 03:49:34 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Tips]]></category>

		<category><![CDATA[jQuery]]></category>

		<category><![CDATA[ujs]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2008/01/14/jquery-embedding-behavior/</guid>
		<description><![CDATA[The fellows over at Err have finally seen the light of jQuery.  My first thought is welcome to the party, we've been wondering when you'd get here.   From my first days with rails, I've been using jQuery over Prototype.  Why? Well, a lot of reasons, but the biggest one is because [...]]]></description>
			<content:encoded><![CDATA[<p>The fellows over at Err have finally <a href="http://errtheblog.com/posts/73-the-jskinny-on-jquery" onclick="javascript:urchinTracker('/outbound/article/errtheblog.com');">seen the light of jQuery</a>.  My first thought is welcome to the party, we've been wondering when you'd get here.   From my first days with rails, I've been using jQuery over Prototype.  Why? Well, a lot of reasons, but the biggest one is because my rails mentor is <a href="http://www.yehudakatz.com" onclick="javascript:urchinTracker('/outbound/article/www.yehudakatz.com');">Yehuda Katz</a>, of <a href="http://www.visualjquery.com" onclick="javascript:urchinTracker('/outbound/article/www.visualjquery.com');">Visual jQuery</a> and <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2FjQuery-Action-Bear-Bibeault%2Fdp%2F1933988355%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1198020280%26sr%3D8-1&tag=kagoyoto-20&linkCode=ur2&camp=1789&creative=9325" onclick="javascript:urchinTracker('/outbound/article/www.amazon.com');">jQuery in Action</a>.  From the first time we met, Yehuda echoed to me exactly what he says in the Err post comment thread.</p>
<blockquote><p>jQuery is a perfect companion to Rails; most people who do any kind of non-trivial JS end up writing custom stuff anyway, and the built-in Rails helpers end up being more trouble than they’re worth.</p></blockquote>
<p>Needless to say, I agree.  In honor of the Chris and PJ jumping to the jQuery camp, I thought I'd answer a thoughtful question in the comments from partage.  I know this is a Ruby blog, but hey, jQuery also saved my life.</p>
<blockquote><p>I’ve also enjoyed mixing jQuery with rails; however, I wonder what techniques people are using to keep the javascript unobtrusive in div replacement scenarios?</p>
<p>To my way of thinking, it sometimes seems natural to package a chunk of markup with the behaviors it needs to operate properly. It’s particularly true when the markup operates as self contained component which may be used several places (for instance, via both partial includes and xhr div replacement).</p>
<p>In those situations, I prefer to call the behavioral javascript at the bottom of the markup rather than trying to ensure I add the behaviors externally (and repeatedly) on all page loads, xhr success handlers, etc. However, I usually suffer a few pangs of guilt with respect to ‘unobtrusive’ javascript.
</p></blockquote>
<p>If I understand correctly, the problem is related to the jQuery methodology of binding events on document ready.</p>
<h2>Basic Event Binding</h2>
<p>The key to remaning unobtrusive with jQuery is to:</p>
<ol>
<li>Select a piece of DOM, i.e <code>$("a.update")</code></li>
<li>Bind something to it, i.e <code>$("a.update").click(function(){ <br />$(this).parent()<br />.load('/posts/'+this.href.split("/").slice(-1)[0].match(/^\d+/))})</code></li>
</ol>
<p>But how and when does this code actually run and get applied to the dom? Well, when the document is ready, as so:</p>
<pre class="javascript">&nbsp;
$<span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;a.update&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">click</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    $<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">parent</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'/posts/'</span>+<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">href</span>.<span style="color: #006600;">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;/&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">slice</span><span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">-1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">match</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066FF;">/^\d+/</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>;
&nbsp;</pre>
<p>Simple, when the document is ready, <code>$(function() {</code>, select all div's with reload, and on click (an event binding), run a function that will load html from an ajax request into the dom that called, the function, represented by <code>$(this)</code>.  From what URL? From /posts/numbers-in-the-id-of-this-div.  What's that mean? Well, I like to do this:</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">for</span> <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#9966CC; font-weight:bold;">in</span> @posts
  <span style="color:#996600;">&quot;
&lt;div id=<span style="color:#000099;">\&quot;</span>post-#{p.id}<span style="color:#000099;">\&quot;</span> class=<span style="color:#000099;">\&quot;</span>reload<span style="color:#000099;">\&quot;</span>&gt;#{p.body}&lt;/div&gt;
&nbsp;
&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>So when you click on that div, it will call /posts/id, which fits in nicely with rails, via ajax.  It will take the result of that request, an replace the html of that div with it.  Awesome. But if you click on that div again, nothing happens. That's because the dom has been replaced and the onclick event that was bound on document ready, no longer exists.  Something must leave instructions for jQuery on what to do next, something must repass behavior instructions.</p>
<h2>Talking Back to jQuery</h2>
<p>In the example above, reloading the div's dom is a trivial feat - as in, you'd really want to use what I'm about to describe for a more complicated situation - for example, if you load a lightbox that has a form in it and which should be submitted via ajax and if validation fails in rails, should display errors and allow for resubmission until success, when it should display a confirmation, close the lightbox, and update some dom.  However, I'm going to continue with the reload example because it's just easier to use, even if it's overkill.</p>
<h3>Callbacks and Simple Rebinds</h3>
<p>The first way to talk back to jQuery, to have the dom reinstruct the script with post-processing, is to use the many opportunities for callbacks and to simply use logic to rebind things.  Now this really only works on the simpler examples, but it's the first option.</p>
<pre class="javascript">&nbsp;
$.<span style="color: #006600;">fn</span>.<span style="color: #006600;">reload_post</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  $<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">click</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    $<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'/posts/'</span>+$<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;id&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">match</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066FF;">/^\d+/</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    $<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">reload_post</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>:
&nbsp;</pre>
<p>The problem with this method is that it's limited in complexity and basically requires a custom function for each implementation - as in that might work for reload_post, but what about reload_comment? But still, that's one options for binding behavior.</p>
<h3>The Tempting but Bad Meta Data Idea</h3>
<p>There is a great, well great in theory, poor in practice, plugin for jQuery called <a href="http://plugins.jquery.com/project/metadata" onclick="javascript:urchinTracker('/outbound/article/plugins.jquery.com');">MetaData</a>.  What it basically allows you to do is embed meta data into DOM.  At first, this is all I used for binding complex behavior to elements.  So I'd have a lot of this in my code:</p>
<pre>&nbsp;
&lt;a href=&quot;/products/share/1&quot; class=&quot;save simple_post {success: NewSavedProduct, dataType: 'json', error: ErrorSimplePost}&quot;&gt;
&lt;a href=&quot;/products/share/2&quot; class=&quot;share simple_post {success: ShareProduct, dataType: 'text', error: ErrorSimplePost}&quot;&gt;
&nbsp;</pre>
<p>At firs,t I thought this was great. I could reuse the same JS function (simple_post - which just creates a POST request from the url of a link), but make it do different things by embedding the options I wanted into the element itself. After about two weeks, I hated it. In the end, it still wasn't flexible enough for me to give complicated instructions, I wasn't reusing that much code as ShareProduct and NewProduct were really custom functions, and in the end, I had totally compromised the semantic nature of my dom. So I nixed that and needed my own solution.  Basically what I wanted were the metadata type options, just out of my dom, so I could reuse functions, load elements with tons of behavior information, but have no trace of that in my source.</p>
<h3>An External Meta File</h3>
<pre class="javascript">&nbsp;
<span style="color: #009900; font-style: italic;">// Button Meta Data</span>
<span style="color: #003366; font-weight: bold;">var</span> simple_post = <span style="color: #66cc66;">&#123;</span>
	save_post: <span style="color: #66cc66;">&#123;</span>
		<span style="color: #66cc66;">&#123;</span>success: NewSavedProduct, dataType: <span style="color: #3366CC;">'json'</span>, error: ErrorSimplePost<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>,
	share_post: <span style="color: #66cc66;">&#123;</span>
		<span style="color: #66cc66;">&#123;</span>success: ShareProduct, dataType: <span style="color: #3366CC;">'text'</span>, error: ErrorSimplePost<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;</pre>
<p>The simple_post function can now use the data stored in this JSON object to instruct itself on what to do based on the link clicked. I've been using this method a great deal for the submit buttons on <a href="http://www.designerpages.com" onclick="javascript:urchinTracker('/outbound/article/www.designerpages.com');">Designer Pages</a>.  There is one function that is bound to all the buttons and that calls a similar type of JSON object to find the instructions for the particular button clicked. This way when I want to add a new behavior for a button, I can just go into that meta.js file and add a new definition. It also integrates nicely with rails helpers. I think there is a lot of potential in this method so I'm going to save the gritty details for another post.</p>
<p>I hope this is a good food-for-thought piece on ways to embed behaviors for your elements in jQuery. In the next week I'll be introducing my first rails plugin <a href="/projects/is_popular/">is_popular</a>, so <a href="http://feeds.feedburner.com/RubySavedMyLife" onclick="javascript:urchinTracker('/outbound/article/feeds.feedburner.com');">subscribe</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2008/01/14/jquery-embedding-behavior/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2008/01/14/jquery-embedding-behavior/</feedburner:origLink></item>
		<item>
		<title>Taking Merb to Production</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/205969091/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/24/taking-merb-to-production/#comments</comments>
		<pubDate>Tue, 25 Dec 2007 07:23:43 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Merb]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/24/taking-merb-to-production/</guid>
		<description><![CDATA[Taking Merb to Production
A good up and running with Merb tutorial.
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.benr75.com/articles/2007/12/24/taking_merb_to_production_nginx_evented_mongrel_capistrano" onclick="javascript:urchinTracker('/outbound/article/www.benr75.com');">Taking Merb to Production</a></p>
<p>A good up and running with Merb tutorial.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/24/taking-merb-to-production/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/24/taking-merb-to-production/</feedburner:origLink></item>
		<item>
		<title>has_many :through: Finding unassociated objects</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/205948989/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/24/has_many-through-finding-unassociated-objects/#comments</comments>
		<pubDate>Tue, 25 Dec 2007 06:06:51 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/24/has_many-through-finding-unassociated-objects/</guid>
		<description><![CDATA[has_many :through: Finding unassociated objects
Awesomeness.
]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.hasmanythrough.com/2006/9/9/finding-unassociated-objects" onclick="javascript:urchinTracker('/outbound/article/blog.hasmanythrough.com');">has_many :through: Finding unassociated objects</a></p>
<p>Awesomeness.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/24/has_many-through-finding-unassociated-objects/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/24/has_many-through-finding-unassociated-objects/</feedburner:origLink></item>
		<item>
		<title>Tip: Return True for Model Hooks</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/202638055/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/19/tip-return-true-for-model-hooks/#comments</comments>
		<pubDate>Wed, 19 Dec 2007 09:45:11 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Tips]]></category>

		<category><![CDATA[ActiveRecord]]></category>

		<category><![CDATA[hooks]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/19/tip-return-true-for-model-hooks/</guid>
		<description><![CDATA[Everyone loves before_create and before_save. Recently it came in very handy for logging hits to objects. If the user is logged in, I want to store the user's full name and the user's type, otherwise, keep those null. So I added this to my PostHit model:
&#160;
def before_create
  if self.user
    self.user_name = [...]]]></description>
			<content:encoded><![CDATA[<p>Everyone loves <code>before_create</code> and <code>before_save</code>. Recently it came in very handy for logging hits to objects. If the user is logged in, I want to store the user's full name and the user's type, otherwise, keep those null. So I added this to my PostHit model:</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> before_create
  <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user_name</span> = <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>.<span style="color:#9900CC;">full_name</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user_type</span> = <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>.<span style="color:#9966CC; font-weight:bold;">class</span>.<span style="color:#9900CC;">name</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p> I fired up my browser to find that the records weren't being created. I was calling them in the Post model via:</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> log_hit<span style="color:#006600; font-weight:bold;">&#40;</span>user = <span style="color:#0000FF; font-weight:bold;">nil</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">hits</span> &lt;&lt; PostHit.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span>:user =&gt; user<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Everything looked right, so what was wrong?</p>
<h2>Before Hits Need to Return True</h2>
<p>In my before_create hook, if user is nil, then the method returns nil, which is false, which prevents the instance from being created.  Thus, return true.</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> before_create
  <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user_name</span> = <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>.<span style="color:#9900CC;">full_name</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user_type</span> = <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">user</span>.<span style="color:#9966CC; font-weight:bold;">class</span>.<span style="color:#9900CC;">name</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">true</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Viola!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/19/tip-return-true-for-model-hooks/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/19/tip-return-true-for-model-hooks/</feedburner:origLink></item>
		<item>
		<title>render_either - the beginning</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/202010146/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/17/render_either-the-beginning/#comments</comments>
		<pubDate>Tue, 18 Dec 2007 04:38:31 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<category><![CDATA[DoubleRenderError]]></category>

		<category><![CDATA[render_either]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/17/render_either-the-beginning/</guid>
		<description><![CDATA[There is this helpful method I've been evolving in my apps for a bit, it's called render_either and it goes a little something like this: (in application.rb)
&#160;
  def render_either&#40;opts = &#123;&#125;&#41;
    # For MIME:Type Recognition
    # respond_to do &#124;f&#124;
    #   f.js {@wants = [...]]]></description>
			<content:encoded><![CDATA[<p>There is this helpful method I've been evolving in my <a href="http://www.designerpages.com" onclick="javascript:urchinTracker('/outbound/article/www.designerpages.com');">apps</a> for a bit, it's called <code>render_either</code> and it goes a little something like this: (in <code>application.rb</code>)</p>
<pre class="ruby">&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> render_either<span style="color:#006600; font-weight:bold;">&#40;</span>opts = <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># For MIME:Type Recognition</span>
    <span style="color:#008000; font-style:italic;"># respond_to do |f|</span>
    <span style="color:#008000; font-style:italic;">#   f.js {@wants = :js}</span>
    <span style="color:#008000; font-style:italic;">#   f.xml {@wants = :xml}</span>
    <span style="color:#008000; font-style:italic;">#   f.html {@wants = :html}</span>
    <span style="color:#008000; font-style:italic;"># end</span>
    <span style="color:#008000; font-style:italic;"># Then use @wants</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> request.<span style="color:#9900CC;">xhr</span>?
      <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:ajax<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:ajax<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:json<span style="color:#006600; font-weight:bold;">&#93;</span>
          render :json =&gt; opts<span style="color:#006600; font-weight:bold;">&#91;</span>:ajax<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:json<span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">to_json</span>
        <span style="color:#9966CC; font-weight:bold;">else</span>
          render opts<span style="color:#006600; font-weight:bold;">&#91;</span>:ajax<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">elsif</span> params<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:redirect_to<span style="color:#006600; font-weight:bold;">&#93;</span>
          redirect_to opts<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:redirect_to<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">else</span>
          render opts<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:default<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">if</span> opts<span style="color:#006600; font-weight:bold;">&#91;</span>:default<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:redirect<span style="color:#006600; font-weight:bold;">&#93;</span>
          redirect_to opts<span style="color:#006600; font-weight:bold;">&#91;</span>:default<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>:redirect<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">else</span>
          render opts<span style="color:#006600; font-weight:bold;">&#91;</span>:default<span style="color:#006600; font-weight:bold;">&#93;</span>
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>This method is very much incomplete - I mean it works - but I want to take it further (and make it prettier and more condensed, but for now, sadly, that's actually more readable to me while I improve it). So why did I write it, what does it do, and why should you care?  Let's say you want to be able to create a Post from a vanilla form, from a lightbox (or an ajax form), and from a bookmarklet. Obviously, you want this all occurring in a <code>PostsController</code> within the <code>new</code> and <code>create</code> methods. Here this is without render_either</p>
<pre class="ruby">&nbsp;
PostsController &lt; ApplicationController
&nbsp;
  <span style="color:#008000; font-style:italic;"># For a vanilla form new.rhtml should be rendered with layout application (default)</span>
  <span style="color:#008000; font-style:italic;"># For a bookmarklet, render new.rhtml but with layout bookmarklet</span>
  <span style="color:#008000; font-style:italic;"># For a lightbox, send back new.rhtml without a layout (so that it back be loaded into a lightbox easily)</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> new
    @post ||= Post.<span style="color:#9900CC;">new</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> request.<span style="color:#9900CC;">xhr</span>?
      render :layout =&gt; <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span> <span style="color:#008000; font-style:italic;"># To prevent DoubleRenderError</span>
    <span style="color:#9966CC; font-weight:bold;">elsif</span> params<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#008000; font-style:italic;">#indicating that this is being loaded in a bookmarklet</span>
      render :layout =&gt; <span style="color:#996600;">&quot;bookmarklet&quot;</span>
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># For a vanilla form, if post is valid, redirect_to post_path(@post),</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot;</span>
  <span style="color:#008000; font-style:italic;"># For a lightbox, if post is valid, render :partial =&gt; &quot;post&quot;,</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot; without layout</span>
  <span style="color:#008000; font-style:italic;"># For a bookmarklet, if post is valid, redirect_to close_bookmarklet_path,</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot;, :layout =&gt; &quot;bookmarklet&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> create
    @post = Post.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:post<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> @post.<span style="color:#9900CC;">save</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> request.<span style="color:#9900CC;">xhr</span>?
        render :partial =&gt; <span style="color:#996600;">&quot;post&quot;</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> params<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span>
        redirect_to close_bookmarklet_path
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">else</span>
        redirect_to post_path
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> request.<span style="color:#9900CC;">xhr</span>?
        render :action =&gt; <span style="color:#996600;">&quot;new&quot;</span>, :layout =&gt; <span style="color:#0000FF; font-weight:bold;">false</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> params<span style="color:#006600; font-weight:bold;">&#91;</span>:bookmarklet<span style="color:#006600; font-weight:bold;">&#93;</span>
        render :action =&gt; <span style="color:#996600;">&quot;new&quot;</span>, :layout =&gt; <span style="color:#996600;">&quot;bookmarklet&quot;</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">else</span>
        render :action =&gt; <span style="color:#996600;">&quot;new&quot;</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Ow, that's painful, right? And that doesn't even deal with some of the added complexities in a real application (returning <code>json</code>, returning <code>xml</code> for <code>api</code> calls, other branches and conditions). The render_either method.</p>
<pre class="ruby">&nbsp;
PostsController &lt; ApplicationController
&nbsp;
  <span style="color:#008000; font-style:italic;"># For a vanilla form new.rhtml should be rendered with layout application (default)</span>
  <span style="color:#008000; font-style:italic;"># For a bookmarklet, render new.rhtml but with layout bookmarklet</span>
  <span style="color:#008000; font-style:italic;"># For a lightbox, send back new.rhtml without a layout (so that it back be loaded into a lightbox easily)</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> new
    @post ||= Post.<span style="color:#9900CC;">new</span>
    render_either :ajax =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:layout =&gt; <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
                  :bookmarklet =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:layout =&gt; <span style="color:#996600;">&quot;bookmarklet&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># For a vanilla form, if post is valid, redirect_to post_path(@post),</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot;</span>
  <span style="color:#008000; font-style:italic;"># For a lightbox, if post is valid, render :partial =&gt; &quot;post&quot;,</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot; without layout</span>
  <span style="color:#008000; font-style:italic;"># For a bookmarklet, if post is valid, redirect_to close_bookmarklet_path,</span>
  <span style="color:#008000; font-style:italic;"># else, render :action =&gt; &quot;new&quot;, :layout =&gt; &quot;bookmarklet&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> create
    @post = Post.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:post<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> @post.<span style="color:#9900CC;">save</span>
      render_either :ajax =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:partial =&gt; <span style="color:#996600;">&quot;post&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
                    :bookmarklet =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:redirect_to =&gt; close_bookmarklet_path<span style="color:#006600; font-weight:bold;">&#125;</span>,
                    :default =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:redirect_to =&gt; post_path<span style="color:#006600; font-weight:bold;">&#40;</span>@post<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      render_either :ajax =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:action =&gt; <span style="color:#996600;">&quot;new&quot;</span>, :layout =&gt; <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#125;</span>,
                    :bookmarklet =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:action =&gt; <span style="color:#996600;">&quot;new&quot;</span>, :layout =&gt; <span style="color:#996600;">&quot;bookmarklet&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
                    :default =&gt; <span style="color:#006600; font-weight:bold;">&#123;</span>:action =&gt; <span style="color:#996600;">&quot;new&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>That's the point of render_either, in a nutshell, to abstract out display logic from a controller.  This is one of the most basic arguments for render_either, and the reason I created it.  I wanted to DRY the logic and remove less if / else branches in a controller action. It then began growing into a stronger package that allows me to do some awesome things with xml and json that I will touch on in later posts.  Let's just say that <a href="http://www.rubysavedmylife.com/2007/12/17/flashnotice-to-the-extreme/" >set_flash</a> loves render_either.  Any questions?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/17/render_either-the-beginning/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/17/render_either-the-beginning/</feedburner:origLink></item>
		<item>
		<title>flash[:notice] to the extreme</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/201950757/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/17/flashnotice-to-the-extreme/#comments</comments>
		<pubDate>Tue, 18 Dec 2007 01:44:12 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<category><![CDATA[flash]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/17/flashnotice-to-the-extreme/</guid>
		<description><![CDATA[I previously discussed the difference between flash.now[:notice] and flash[:notice]. I ended with a summarizing rule that says when you end an action with render, you generally want to use flash.now[:notice], and when you end an action with redirect, you want to use flash[:notice]. While simple, I hate remembering that rule, and what really complicates things [...]]]></description>
			<content:encoded><![CDATA[<p>I previously discussed the <a href="http://www.rubysavedmylife.com/2007/12/15/flashnotice-vs-flashnownotice/" >difference between flash.now[:notice] and flash[:notice]</a>. I ended with a summarizing rule that says when you end an action with render, you generally want to use flash.now[:notice], and when you end an action with redirect, you want to use flash[:notice]. While simple, I hate remembering that rule, and what really complicates things is request.xhr?</p>
<pre class="ruby">&nbsp;
<span style="color:#008000; font-style:italic;"># Toward the end of an action in a controller</span>
<span style="color:#9966CC; font-weight:bold;">if</span> request.<span style="color:#9900CC;">xhr</span>?
  flash.<span style="color:#9900CC;">now</span><span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;Action Completed&quot;</span>
<span style="color:#9966CC; font-weight:bold;">else</span>
  flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;Action completed.&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>An Ajax Request (XHR) always should use flash.now.  Why? Because if it's an ajax request, then the page was not reloaded, which means if you set flash[:notice], whatever request comes next from the user, will load with the flash[:notice] of the last request, which in this case, is an XHR request - in short, they will see a persistent, non-relevant, flash[:notice] from the ajax call. So the rule for choosing whether to use flash.now or flash becomes: <strong>If an action is a response to an ajax request, or if it ends with a render, use flash.now, otherwise use flash.</strong></p>
<h2>But That's Complicated!</h2>
<p>True, it is complicated and requires a lot of conditional logic in your controllers.  The truth is, the choice between flash and flash.now should be abstracted out.  A controller should not be responsible for choosing whether to flash or flash.now.</p>
<h2>set_flash</h2>
<p>In <code>application.rb</code> define the following function.</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> set_flash<span style="color:#006600; font-weight:bold;">&#40;</span>options=<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  now = options<span style="color:#006600; font-weight:bold;">&#91;</span>:now<span style="color:#006600; font-weight:bold;">&#93;</span> || <span style="color:#006600; font-weight:bold;">&#40;</span>request.<span style="color:#9900CC;">xhr</span>? ? <span style="color:#0000FF; font-weight:bold;">true</span> : <span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> now
    flash.<span style="color:#9900CC;">now</span><span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = options
  <span style="color:#9966CC; font-weight:bold;">else</span>
    flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = options
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>A simple, but powerful and helpful function. Instead of having to call flash.now or flash, you can just do this in your controllers (as opposed to the example above).</p>
<pre class="ruby">&nbsp;
<span style="color:#008000; font-style:italic;"># Towards the end of an action in a controller</span>
set_flash :text =&gt; <span style="color:#996600;">&quot;Action Completed&quot;</span>
&nbsp;</pre>
<p>See, no more checks for request.xhr? because set_flash has that check. Of course, you can easily override that if you wanted an xhr request to flash and not flash.now.</p>
<pre class="ruby">&nbsp;
set_flash :text =&gt; <span style="color:#996600;">&quot;Action Completed&quot;</span>, :now =&gt; <span style="color:#0000FF; font-weight:bold;">true</span>
&nbsp;</pre>
<p>What I really love about the <code>set_flash</code> method is the ability to nicely constructed flash's with a lot of meta data:</p>
<pre class="ruby">&nbsp;
set_flash :klass =&gt; <span style="color:#996600;">&quot;error&quot;</span>,
             :text =&gt; <span style="color:#996600;">&quot;Registration failed&quot;</span>,
             :alt =&gt; <span style="color:#996600;">&quot;Did you fill out the form correctly?&quot;</span>
&nbsp;</pre>
<p>I can then build a helper method in application_helper.rb to print out a formatted flash</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> formatted_flash
 <span style="color:#996600;">&quot;
&lt;h2 class=<span style="color:#000099;">\&quot;</span>#{flash[:notice][:klass] || &quot;</span>success<span style="color:#996600;">&quot;}<span style="color:#000099;">\&quot;</span>&gt;#{flash[:notice][:text]}&lt;span&gt;#{flash[:notice][:alt]}&lt;/span&gt;&lt;/h2&gt;
&nbsp;
&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Obviously, you can customize this method to handle a lot of how to format the flash message logic and you can add your keys to your flash[:notice], like type (a flash isn't always a notice, maybe it's a warning). Don't settle for an unintelligent, string-based flash notice.</p>
<p><em>Excuse the shoddy formatting above, I'm working on it <img src='http://www.rubysavedmylife.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/17/flashnotice-to-the-extreme/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/17/flashnotice-to-the-extreme/</feedburner:origLink></item>
		<item>
		<title>Flash[:notice] vs Flash.now[:notice]</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/200941017/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/15/flashnotice-vs-flashnownotice/#comments</comments>
		<pubDate>Sat, 15 Dec 2007 21:41:48 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/2007/12/15/flashnotice-vs-flashnownotice/</guid>
		<description><![CDATA[
You're just starting on rails and you're very excited about the ease of flash[:notice].  But every now and then, you set a flash notice and it seems to follow your clicks to the next action when it shouldn't.  Why? I'll tell you.

Intro to flash[:notice]
flash[:notice] belongs to FlashHash.The basic use of the flash hash [...]]]></description>
			<content:encoded><![CDATA[<p>
You're just starting on rails and you're very excited about the ease of flash[:notice].  But every now and then, you set a flash notice and it seems to follow your clicks to the next action when it shouldn't.  Why? I'll tell you.
</p>
<h2>Intro to flash[:notice]</h2>
<p>flash[:notice] belongs to <a href="http://api.rubyonrails.org/classes/ActionController/Flash/FlashHash.html" onclick="javascript:urchinTracker('/outbound/article/api.rubyonrails.org');">FlashHash</a>.The basic use of the flash hash is flash[:notice], a place to put a message that describes the result of an action in a rails app.  Let's look at an example:
</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> WeblogController &lt; ActionController::Base
  <span style="color:#9966CC; font-weight:bold;">def</span> create
    @post = Post.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:post<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> @post.<span style="color:#9900CC;">save</span>
      flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;#{@post.title} has been created.&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span>= <span style="color:#996600;">&quot;#{@post.title} could not be created.&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>
Pretty self explanatory.  However, things get a bit complicated when you think about what that method should be doing.  If the post is successfully created, the method should redirect_to post_path(@post), else, render :action => "new".  The new action will fill the form in using the already initialized @post object (and it's errors) and the flash message will let them know that there was a problem.  So let's add that in real quick:
</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> WeblogController &lt; ActionController::Base
  <span style="color:#9966CC; font-weight:bold;">def</span> create
    @post = Post.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:post<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> @post.<span style="color:#9900CC;">save</span>
      flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;#{@post.title} has been created.&quot;</span>
      redirect_to post_path<span style="color:#006600; font-weight:bold;">&#40;</span>@post<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span>= <span style="color:#996600;">&quot;#{@post.title} could not be created.&quot;</span>
      render :action =&gt; <span style="color:#996600;">&quot;new&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>
Now flash[:notice] becomes a problem. When the user sees there was an error creating the post, he decided to abandon the process and move onto a different page in your application.  Well, what's going to happen is that on the next page, he is going to see the same flash[:notice] he just saw notifying him of the error.
</p>
<h2>Flash Right Now</h2>
<p>The Flash hash by default persists to the next action.  That's what it's suppose to do - it's a way to send a message to the next action.  However, in our create post example, if the post fails creation, there is no next action, rather, the create action simply renders the new action, a very common pattern.  That's why when the user moves to another page, the flash[:notice] persists, because that other page is the next action.  Obviously, you want to avoid that, and that's exactly what flash.now is for:</p>
<pre class="ruby">&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> WeblogController &lt; ActionController::Base
  <span style="color:#9966CC; font-weight:bold;">def</span> create
    @post = Post.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:post<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> @post.<span style="color:#9900CC;">save</span>
      flash<span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;#{@post.title} has been created.&quot;</span>
      redirect_to post_path<span style="color:#006600; font-weight:bold;">&#40;</span>@post<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      flash.<span style="color:#9900CC;">now</span><span style="color:#006600; font-weight:bold;">&#91;</span>:notice<span style="color:#006600; font-weight:bold;">&#93;</span>= <span style="color:#996600;">&quot;#{@post.title} could not be created.&quot;</span>
      render :action =&gt; <span style="color:#996600;">&quot;new&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>A basic rule to know when to use flash[:notice] and when to use flash.now[:notice] is if the action is redirecting - redirect_to - use flash[:notice], if it's rendering - render :action - use flash.now[:notice]. This is really just the beginning of the power of the flash object. Stay tuned for some more posts on how to really make use of this great feature in rails.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/15/flashnotice-vs-flashnownotice/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/15/flashnotice-vs-flashnownotice/</feedburner:origLink></item>
		<item>
		<title>Chaining Create Methods to an Object Instance</title>
		<link>http://feeds.feedburner.com/~r/RubySavedMyLife/~3/200141209/</link>
		<comments>http://www.rubysavedmylife.com/2007/12/13/chaining-create-methods-to-an-object-instance/#comments</comments>
		<pubDate>Fri, 14 Dec 2007 04:39:57 +0000</pubDate>
		<dc:creator>Avi Flombaum</dc:creator>
		
		<category><![CDATA[Rails]]></category>

		<category><![CDATA[ActiveRecord]]></category>

		<category><![CDATA[Controller]]></category>

		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://www.rubysavedmylife.com/?p=4</guid>
		<description><![CDATA[In my Rails controllers, I have a lot of this:
&#160;
@project = Project.find&#40;params&#91;:project&#93;&#41;
if @project
  @project_product = @project.project_products.create&#40;params&#91;:project_product&#93;&#41;
  if @project_product.valid?
   # Do something with success
  else
   # Do something with error
  end
else
  # Do something with error
end
&#160;
The thing that I don't like about that style is that the [...]]]></description>
			<content:encoded><![CDATA[<p>In my Rails controllers, I have a lot of this:</p>
<pre class="ruby">&nbsp;
@project = Project.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:project<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">if</span> @project
  @project_product = @project.<span style="color:#9900CC;">project_products</span>.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:project_product<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> @project_product.<span style="color:#9900CC;">valid</span>?
   <span style="color:#008000; font-style:italic;"># Do something with success</span>
  <span style="color:#9966CC; font-weight:bold;">else</span>
   <span style="color:#008000; font-style:italic;"># Do something with error</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">else</span>
  <span style="color:#008000; font-style:italic;"># Do something with error</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>The thing that I don't like about that style is that the controller is validating the creation of a ProjectProduct.  There is the conditional " if @project " branch that basically says that the ProjectProduct requires a valid Project.  I feel like the controller shouldn't be the one to determine that - this isn't a case of validating params (like if you preventing url hacking).  Rails sort of even lets you know that you shouldn't be using that syntax because attaching the error to @project_product (which you would be sending back to the form as an error message), is impossible as @project_product hasn't even been initiated yet.</p>
<p>For these reasons I have no opted to do something like this:</p>
<p>(assuming ProjectProduct.rb validates the presence of :project, which it should - that's the entire point, that the model in this case should be requiring the existence of a project for ProjectProduct, not the controller)</p>
<pre class="ruby">&nbsp;
@project = Project.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:project<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
@project_product = ProjectProduct.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span>params<span style="color:#006600; font-weight:bold;">&#91;</span>:project_product<span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">merge</span><span style="color:#006600; font-weight:bold;">&#40;</span>:project =&gt; @project<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">if</span> @project_product.<span style="color:#9900CC;">valid</span>?
  <span style="color:#008000; font-style:italic;"># Do something with success</span>
<span style="color:#9966CC; font-weight:bold;">else</span>
  <span style="color:#008000; font-style:italic;"># Do something with error</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Benefits to this:</p>
<ol>
<li>Shorter Controller Method</li>
<li>One less conditional branch</li>
<li>Validation by Model and not Controller</li>
<li>No hacks to get Rails to generate error message for you.</li>
</ol>
<p>A new best practice for myself.</p>
<li>
]]></content:encoded>
			<wfw:commentRss>http://www.rubysavedmylife.com/2007/12/13/chaining-create-methods-to-an-object-instance/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.rubysavedmylife.com/2007/12/13/chaining-create-methods-to-an-object-instance/</feedburner:origLink></item>
	</channel>
</rss>
