<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.1" -->
<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>nuclearpanda.com</title>
	<link>http://blog.nuclearpanda.com</link>
	<description></description>
	<pubDate>Wed, 23 Jan 2008 04:52:27 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<item>
		<title>Django method rename without documentation update just ate hours of my life</title>
		<link>http://blog.nuclearpanda.com/2008/01/23/django-method-rename-just-ate-hours-of-my-life/</link>
		<comments>http://blog.nuclearpanda.com/2008/01/23/django-method-rename-just-ate-hours-of-my-life/#comments</comments>
		<pubDate>Wed, 23 Jan 2008 04:50:32 +0000</pubDate>
		<dc:creator>ikai</dc:creator>
		
		<category><![CDATA[Django]]></category>

		<category><![CDATA[Python]]></category>

		<category><![CDATA[django python newforms forms clean_data cleaned_data]]></category>

		<guid isPermaLink="false">http://blog.nuclearpanda.com/2008/01/23/django-method-rename-just-ate-hours-of-my-life/</guid>
		<description><![CDATA[I&#8217;m a Rails guy, but I&#8217;m not married to the framework. I honestly believe that no one should isolate themselves from the greater community, because one misses great learning opportunities.
So I&#8217;ve been learning Django. My goal is to put together the most comprehensive breakdown of Rails vs. Django, not to start a flame war, rather, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a Rails guy, but I&#8217;m not married to the framework. I honestly believe that no one should isolate themselves from the greater community, because one misses great learning opportunities.</p>
<p>So I&#8217;ve been learning Django. My goal is to put together the most comprehensive breakdown of Rails vs. Django, not to start a flame war, rather, to really inspect each framework so that each can benefit from innovations in the other.</p>
<p>I was working on some forms (one of my biggest complaints about Django is that everything is so explicit - &#8216;convention over configuration&#8217; isn&#8217;t exactly the highest priority in the framework. This can be both a plus and a minus) - following this guide: http://www.djangoproject.com/documentation/0.96/newforms/</p>
<p>Apparently, <strong>clean_data</strong> has been renamed to <strong>cleaned_data</strong>. Yikes! This isn&#8217;t a new change, either (http://eggdrop.ch/blog/2007/02/15/django-dynamicforms/). This has been around since February.</p>
<p>Say what you will about the Rails community, at least renamed functions give a deprecation warning. Since the Django development server provides no logging information in its output, this wouldn&#8217;t apply. This isn&#8217;t going to discourage me from learning Django, but I am certainly going to note it in my list of evidence that the framework is far from mature.</p>
<p><strong> Edit: I just saw that I&#8217;m not the only one who saw this. This was apparently in the little popup notes. </strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2008/01/23/django-method-rename-just-ate-hours-of-my-life/feed/</wfw:commentRss>
		</item>
		<item>
		<title>OS X Beanstalkd compile issues</title>
		<link>http://blog.nuclearpanda.com/2008/01/10/os-x-beanstalkd-compile-issues/</link>
		<comments>http://blog.nuclearpanda.com/2008/01/10/os-x-beanstalkd-compile-issues/#comments</comments>
		<pubDate>Thu, 10 Jan 2008 18:41:07 +0000</pubDate>
		<dc:creator>ikai</dc:creator>
		
		<category><![CDATA[Linux]]></category>

		<category><![CDATA[Mac OS X]]></category>

		<guid isPermaLink="false">http://blog.nuclearpanda.com/2008/01/10/os-x-beanstalkd-compile-issues/</guid>
		<description><![CDATA[I ran into a few problems compiling Beankstalkd on OS X. I kept seeing:
Makefile:9: *** multiple target patterns.  Stop.
After some searching, I referred to this thread on the Beanstalkd mailing list: http://groups.google.com/group/beanstalk-talk/browse_thread/thread/3351a425342fe09f/159178b5c5be2849?lnk=gst&#38;q=make#159178b5c5be2849
Basicaly, all I had to do was update gmake:
sudo port install gmake
Set environment variables:
export C_INCLUDE_PATH=/opt/local/include
export LIBRARY_PATH=/opt/local/lib
Then:
gmake
Done!
]]></description>
			<content:encoded><![CDATA[<p>I ran into a few problems compiling Beankstalkd on OS X. I kept seeing:</p>
<p>Makefile:9: *** multiple target patterns.  Stop.</p>
<p>After some searching, I referred to this thread on the Beanstalkd mailing list: http://groups.google.com/group/beanstalk-talk/browse_thread/thread/3351a425342fe09f/159178b5c5be2849?lnk=gst&amp;q=make#159178b5c5be2849</p>
<p>Basicaly, all I had to do was update gmake:</p>
<p>sudo port install gmake</p>
<p>Set environment variables:</p>
<p>export C_INCLUDE_PATH=/opt/local/include<br />
export LIBRARY_PATH=/opt/local/lib</p>
<p>Then:</p>
<p>gmake</p>
<p>Done!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2008/01/10/os-x-beanstalkd-compile-issues/feed/</wfw:commentRss>
		</item>
		<item>
		<title>CacheSweepers and url_for</title>
		<link>http://blog.nuclearpanda.com/2007/12/31/cachesweepers-and-url_for/</link>
		<comments>http://blog.nuclearpanda.com/2007/12/31/cachesweepers-and-url_for/#comments</comments>
		<pubDate>Mon, 31 Dec 2007 01:39:31 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[ActionController]]></category>

		<category><![CDATA[ActionView]]></category>

		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://blog.nuclearpanda.com/2007/12/31/cachesweepers-and-url_for/</guid>
		<description><![CDATA[It appears url_for only seems to work correctly in a CacheSweeper when running a server in production mode. I&#8217;ve confirmed this in Rails 2.0.2.

class MySeeper &#60; ActionController::Caching::Sweeper
	observe Item

	def after_create(item)
	   value = url_for(:controller =&#62; :items)
	end
end
In development mode, value evaluates to nil. Peculiar indeed &#8230;
]]></description>
			<content:encoded><![CDATA[<p>It appears url_for only seems to work correctly in a CacheSweeper when running a server in production mode. I&#8217;ve confirmed this in Rails 2.0.2.</p>
<pre name="code" class="ruby">
class MySeeper &lt; ActionController::Caching::Sweeper
	observe Item

	def after_create(item)
	   value = url_for(:controller =&gt; :items)
	end
end</pre>
<p>In development mode, value evaluates to nil. Peculiar indeed &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/12/31/cachesweepers-and-url_for/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Autotest with growl</title>
		<link>http://blog.nuclearpanda.com/2007/12/17/autotest-with-growl/</link>
		<comments>http://blog.nuclearpanda.com/2007/12/17/autotest-with-growl/#comments</comments>
		<pubDate>Mon, 17 Dec 2007 20:58:19 +0000</pubDate>
		<dc:creator>ikai</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=4</guid>
		<description><![CDATA[Here is my .autotest file. It&#8217;s based on John Nunemaker&#8217;s guide:

module Autotest::Growl
  IMAGE_ROOT = "~/.autotest_images" 

  def self.growld title, msg, img, pri=0, sticky=""
    system "growlnotify -n autotest --image #{img} -p #{pri} -m #{msg.inspect} #{title} #{sticky}"
  end

  Autotest.add_hook :green do &#124;at&#124;
    results = [at.results].flatten.join("\n")
   [...]]]></description>
			<content:encoded><![CDATA[<p>Here is my .autotest file. It&#8217;s based on <a href="http://railstips.org/2007/7/23/autotest-growl-pass-fail-notifications">John Nunemaker&#8217;s guide</a>:</p>
<pre name="code" class="ruby">
module Autotest::Growl
  IMAGE_ROOT = "~/.autotest_images" 

  def self.growld title, msg, img, pri=0, sticky=""
    system "growlnotify -n autotest --image #{img} -p #{pri} -m #{msg.inspect} #{title} #{sticky}"
  end

  Autotest.add_hook :green do |at|
    results = [at.results].flatten.join("\n")
    output = results.slice(/\d+ examples, \d+ failures, \d+ pending/)
    growld "Pass", output, "#{IMAGE_ROOT}/pass.png"
  end

  Autotest.add_hook :red do |at|
    results = [at.results].flatten.join("\n")
    output = results.slice(/\d+ examples, \d+ failures, \d+ pending/)
    growld "Fail", output, "#{IMAGE_ROOT}/fail.png"
  end

end</pre>
<p>I had to change his code for a few reasons: first, the string regex didn&#8217;t match what I was getting in Rspec. Also, requiring &#8216;autotest/growl&#8217; in the latest version of ZenTest (I&#8217;m on 3.6.1) adds an extraneous failure message before the  :red hook fires off.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/12/17/autotest-with-growl/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Enumerable#sort</title>
		<link>http://blog.nuclearpanda.com/2007/12/12/enumerablesort/</link>
		<comments>http://blog.nuclearpanda.com/2007/12/12/enumerablesort/#comments</comments>
		<pubDate>Wed, 12 Dec 2007 23:27:16 +0000</pubDate>
		<dc:creator>ikai</dc:creator>
		
		<category><![CDATA[ActiveRecord]]></category>

		<category><![CDATA[Rails]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=3</guid>
		<description><![CDATA[In Ruby, to sort a collection of Objects, the &#60;=&#62; method needs to be defined. Suppose we have the following:
# has a field created_at, which is a datetime
class Event &#60; ActiveRecord::Base
end
Let&#8217;s say we want to do the following:
@events = Event.find(:all)
@events.sort
To do this, we would need to define the &#60;=&#62; method in Event:
class Event &#60; ActiveRecord::Base
 [...]]]></description>
			<content:encoded><![CDATA[<p>In Ruby, to sort a collection of Objects, the &lt;=&gt; method needs to be defined. Suppose we have the following:</p>
<pre name="code" class="ruby"># has a field created_at, which is a datetime
class Event &lt; ActiveRecord::Base
end</pre>
<p>Let&#8217;s say we want to do the following:</p>
<pre name="code" class="ruby">@events = Event.find(:all)
@events.sort</pre>
<p>To do this, we would need to define the &lt;=&gt; method in Event:</p>
<pre name="code" class="ruby">class Event &lt; ActiveRecord::Base
  def &lt;=&gt;(event)
    created_at &lt;=&gt; event.created_at
  end
end</pre>
<p>By created a &lt;=&gt; method for Event objects, the Enumerable#sort method now knows which value to sort on; rather, in this example, by elegantly delegating the sorting to some magic Time comparison methods in Ruby that we don&#8217;t need to know about.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/12/12/enumerablesort/feed/</wfw:commentRss>
		</item>
		<item>
		<title>AJAX forms and file uploading in Rails</title>
		<link>http://blog.nuclearpanda.com/2007/09/20/ajax-forms-and-file-uploading-in-rails/</link>
		<comments>http://blog.nuclearpanda.com/2007/09/20/ajax-forms-and-file-uploading-in-rails/#comments</comments>
		<pubDate>Thu, 20 Sep 2007 00:16:35 +0000</pubDate>
		<dc:creator>Ikai Lan</dc:creator>
		
		<category><![CDATA[AJAX]]></category>

		<category><![CDATA[ActionView]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=11</guid>
		<description><![CDATA[One very nice thing about Ruby on Rails is the support for AJAX. I consider myself a backend guy, so I don’t generally like to touch Javascript (though I’ve written my fair share of XMLHttpRequest calls without the help of frameworks - which is probably why I dislike Javascript so much).
&#160;
The other day I was [...]]]></description>
			<content:encoded><![CDATA[<p>One very nice thing about Ruby on Rails is the support for AJAX. I consider myself a backend guy, so I don’t generally like to touch Javascript (though I’ve written my fair share of XMLHttpRequest calls without the help of frameworks - which is probably why I dislike Javascript so much).</p>
<p class="entry">&nbsp;</p>
<p class="snap_preview">The other day I was working on AJAXifying some forms, because it didn’t make sense to refresh the entire browser window for these functions. Here’s my original view:</p>
<pre name="code" class="ruby">&lt;% form_for :message, :url =&gt;{:controller =&gt; :message,:action =&gt; :post },
:html =&gt; { :multipart =&gt; true } do |form| %&gt;
&lt;% fields_for :image do |image| %&gt;
&lt;%= image.file_field :file_data, :size =&gt; 20  %&gt;
&lt;% end %&gt;
&lt;%= form.text_area :body, :cols =&gt; 40, :rows =&gt; 2 %&gt;
&lt;%= submit_tag "Send", :class =&gt; :submit %&gt;
&lt;% end %&gt;</pre>
<p>Pretty straightforward stuff. The controller method wasn’t much more complex:</p>
<p>MessageController.rb</p>
<pre name="code" class="ruby">def send
if request.post?
  @message = Message.new(params[:message])
  unless params[:image].blank? or
    params[:image][:file_data].blank?
    @message.images &lt;&lt; Image.new(params[:image])
  end
  @message.save
end
end</pre>
<p>I won’t get too much into the Message or Image models; these can be found anywhere. A decent Image model is available inside the Rails Recipes book. As a rule of thumb, NEVER start your development with AJAX. Javascript can be a harsh mistress, and you’re better off degrading to a non-AJAX page that fully functions rather than running into Javascript problems and having to rebuild anyway.</p>
<p>The very first thing I did was change the form. Instead of using form_for, I changed it to form_remote_for. No problems!</p>
<pre name="code" class="ruby">&lt;% form_remote_for :message, :url =&gt; {:controller =&gt; :message, :action =&gt; :post },
:html =&gt; { :multipart =&gt; true } do |form| %&gt;

&lt;% fields_for :image do |image| %&gt;
&lt;%= image.file_field :file_data, :size =&gt; 20  %&gt;
&lt;% end %&gt;
&lt;%= form.text_area :body, :cols =&gt; 40, :rows =&gt; 2 %&gt;
&lt;%= submit_tag "Send", :class =&gt; :submit %&gt;
&lt;% end %&gt;</pre>
<p>As you can see all I’ve done here is change the method name. A quick ‘tail -f development.log’ shows us that the form is indeed being sent to the server. But what is the point of AJAX without some crazy cool thing going asynchronously? Rails makes this easy too:</p>
<pre name="code" class="ruby">&lt;% form_remote_for :message, :url =&gt;
 {:controller =&gt; :message,
 :action =&gt; :post },
 :loading =&gt; "Element.show('status')",
 :success =&gt; "Element.hide('status')",
 :html =&gt; { :multipart =&gt; true } do |form| %&gt;
&lt;% fields_for :image do |image| %&gt;
&lt;%= image.file_field :file_data, :size =&gt; 20  %&gt;
&lt;% end %&gt;
&lt;%= form.text_area :body, :cols =&gt; 40, :rows =&gt; 2 %&gt;
&lt;%= submit_tag "Send", :class =&gt; :submit %&gt;
&lt;% end %&gt;
&lt;div id='status' style='display:none;'&gt;Sending ...&lt;/div&gt;
&lt;div id='last_sent_message' style='display:none;'&gt;
&lt;/div&gt;</pre>
<p>Let’s also  make the controller render an RJS template:</p>
<p>send.rjs</p>
<pre name="code" class="ruby">page.replace_html “last_sent_message”, :partial =&gt;’message’, :object =&gt; @message</pre>
<p>Again, I won’t bore you with the details of the partial or the models. For the most part, this did what I needed it to do … until I tried to upload an Image. Exception throwing time …</p>
<p>This is where Google comes in. The best link I could find for Rails AJAX file uploading was Dave Naffis’s Rails blog:</p>
<p><a href="http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments" title="http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments">http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments</a></p>
<p>The primary takeaway here is that pure Javascript form uploading is impossible because Javascript does not have access to a client filesystem (for security reasons), and thus, file form fields. To work around this, sites that allow “AJAX” file uploads are actually posting to an IFRAME, not sending the file via XHR.</p>
<p>Dave does a pretty good job, but as he says in his blog, he wrote the code in about 20 minutes. To allow AJAX like file uploads, you must do the following:</p>
<p>1. Install the Responds to Parent plugin. This allows any RJS rendered in an IFRAME to access the DOM of the parent document. This is not mandatory, but it allows the POST response to manipulate the main page to show that an upload completed (or whatever … ).</p>
<p><a href="http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments" title="http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments">http://agilewebdevelopment.com/plugins/responds_to_parent</a></p>
<p>To install, type:</p>
<pre>ruby script/plugin      <a href="http://sean.treadway.info/svn/plugins/responds_to_parent/">http://sean.treadway.info/svn/plugins/responds_to_parent/</a></pre>
<p>2. Create a file called ‘remote_uploads.rb’ in your lib/ directory. Dave Naffis has a version of code on his site, but I’ve gone the extra step and modified it a bit:</p>
<pre name="code" class="ruby">module ActionView
  module Helpers
    module PrototypeHelper
      alias :form_remote_tag_old :form_remote_tag
      def form_remote_tag(options = {}, &amp;block)
        unless options[:html] &amp;&amp; options[:html][:multipart]
           form_remote_tag_old(options, &amp;block)
        else
          uid = "a#{Time.now.to_f.hash}"
          &lt;&lt;-STR
<form method="post"> true})}” enctype=”multipart/form-data” target=”#{uid}” #{%(onsubmit=”#{options[:loading]}”) if options[:loading]}&gt;
          STR
        end
      end
    end
  end
end</form>
</pre>
<p>There were two problem with the original code, at least for me. First, nothing inside the form_for{} block was being rendered for some reason for a regular, non-multipart form. The method has been changed to accept &amp;block as a second parameter, and pass this along appropriate to form_for.</p>
<p>The second problem was that, for whatever reason, in the original code, form_remote_tag_old just seemed to never get called. I didn’t have time to debug this, and I’m going to be accused of being incomplete, but reversing the IF and the UNLESS solved this problem for me.</p>
<p>3. Add</p>
<pre><code>require 'remote_uploads.rb'</code></pre>
<p>To environment.rb.</p>
<p>4. Change the controller action to render the response in a responds_to_parent block:</p>
<pre name="code" class="ruby">def send
  if request.post?
    @message = Message.new(params[:message])
    unless params[:image].blank? or
        params[:image][:file_data].blank?
      @message.images &lt;&lt; Image.new(params[:image])
    end
    @message.save
    responds_to_parent do
      render :action =&gt; 'post.rjs'
    end
  end
end</pre>
<p>5. Restart your server to load the environment.rb changes.</p>
<p>Voila! You are done. More importantly, “AJAX” form uploads are now enabled in the future anytime you call form_remote_tag with :html =&gt; { :multipart =&gt; true }.</p>
<p>Now go out there and write some form_remote_tag forms with pseudo-AJAX uploads!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/09/20/ajax-forms-and-file-uploading-in-rails/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby Procs: Part I</title>
		<link>http://blog.nuclearpanda.com/2007/08/30/ruby-procs-part-i/</link>
		<comments>http://blog.nuclearpanda.com/2007/08/30/ruby-procs-part-i/#comments</comments>
		<pubDate>Thu, 30 Aug 2007 21:25:03 +0000</pubDate>
		<dc:creator>Ikai Lan</dc:creator>
		
		<category><![CDATA[Object-Oriented Programming]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=10</guid>
		<description><![CDATA[In high school, I had a computer programming teacher who described variables as &#8216;mailboxes&#8217;, with values being &#8216;postcards&#8217;. In my four years of college, I don&#8217;t think I&#8217;ve ever heard that term or comparison again - though, in retrospect, I think the &#8216;mailbox&#8217; analogy helped my understanding of more advanced variable topics, such as pointers [...]]]></description>
			<content:encoded><![CDATA[<p>In high school, I had a computer programming teacher who described variables as &#8216;mailboxes&#8217;, with values being &#8216;postcards&#8217;. In my four years of college, I don&#8217;t think I&#8217;ve ever heard that term or comparison again - though, in retrospect, I think the &#8216;mailbox&#8217; analogy helped my understanding of more advanced variable topics, such as pointers (a postcard with another mailbox&#8217;s address) or pass-by-reference (a postcard with instructions to read another postcard at another mailbox).  Interestingly enough, as I became a more advanced developer, I forgot about the mailbox analogy, because I didn&#8217;t need it anymore to understand what I was doing.</p>
<p>Recently, I started working with Ruby Procs. Ruby Procs aren&#8217;t explained very well, at least not in any book or website I&#8217;ve read, so I&#8217;ll do my best to explain what a Proc is. Incidentally, I find that the &#8216;mailbox&#8217; analogy works pretty well again: a &#8216;Proc&#8217; is a postcard with a set of instructions that the Postman must obey (or, I&#8217;d imagine, suffer some horrible fate). Come again? Maybe I need to rewind a bit and talk in code &#8230;</p>
<p>Anyone that has been working with Ruby for a bit is familiar with the concept of &#8216;yield&#8217; and &#8216;blocks&#8217;. First, the block:</p>
<pre name="code" class="ruby">
  array = [1,2,3]
  array.each do { |value| puts 'Doing stuff.' }
</pre>
<p>The code between the brackets {} is a block. This same code can be written as:</p>
<pre name="code" class="ruby">
array.each do |value|
  puts 'Doing stuff.'
end</pre>
<p>A block is a block of code, is a block of code, is a block of code. Nothing too special see here.</p>
<p>But let&#8217;s combine the block of code with the yield statement:</p>
<pre name="code" class="ruby">def is_polygamous?
  if yield &gt;= 1
   true
  else
   false
end
my_wives = 5</pre>
<p>The block of code:</p>
<pre name="code" class="ruby">is_polygamous? { my_wives }</pre>
<p>Would thus produce true. Yield effectively takes the block of code after the method call, evaluates the code inside in the <strong>context of the calling scope</strong>, and executes it. This seems kind of pointless - why would anyone write a method this way, when we could simply have passed the value as a parameter? For starters, the code inside the block is <strong>not called until the function reaches the yield statement</strong>. Let&#8217;s look at another example:</p>
<pre name="code" class="ruby">def power_rangers_right
    puts 'Go, go'
    yield
end
def power_rangers_wrong(output_method)
    puts 'Go, go'
    output_method
end</pre>
<p>Now let&#8217;s call each of the methods, passing puts(&#8217;Power Rangers!&#8217;)  as a parameter:</p>
<pre name="code" class="ruby">power_rangers_right { puts('Power Rangers!')}</pre>
<p><strong>output: Go, go<br />
Power Rangers!</strong><br />
power_rangers_wrong(puts(&#8217;Power Rangers!&#8217;))</pre>
<pre>
<strong> output:
Power Rangers!
Go, go</strong></pre>
<p>As you can see, when you pass a parameter into a method, the code is executed before the method is actually called. When we use yield and code blocks, the execution is deferred until the method reaches the yield statement.</p>
<p>The reason I went into this long winded discussion about blocks and yields is because a function block is a Proc object. The function definition, power_rangers_right, implicitly carries a parameter in the form of power_rangers_right(&amp;proc_object).</p>
<p>The real power behind the Proc, however, is not just that it is a block of code whose execution is deferred. The real power behind Proc is that Proc is a standard Ruby Object. Yes, that&#8217;s right, a Proc is a standard Ruby Object and can be passed in a method parameter, people - thus, the mailbox analogy applies. Let&#8217;s look at an actual non-trivial example of this in action:</p>
<pre name="code" class="ruby">
def Lion
end

def TinMan
end

def Scarecrow
end

def JustinTimberlake
end

def wants?(person_type)
   types_i_know = { :Lion =&gt; 'Courage',  :TinMan =&gt; 'A Heart', :Scarecrow =&gt; 'Brain'}
   complaint = Proc.new { raise ArgumentError("I don't know what #{person_type} wants.")}
   types_i_know.find(complaint) { |person, value| person.is_a?(Object.const_for(person))}.last
end</pre>
<p>There&#8217;s a lot of code going on here, so I&#8217;ll break down what we are trying to accomplish. We want to pass a class of person to a method wants?, which returns what that Person truly desires. To do this, we look up values against a Hash. If we do not know what the person wants, we want to raise an Exception. Line by line, this is what we are doing:</p>
<pre name="code" class="ruby">   complaint = Proc.new { raise ArgumentError("I don't know what #{person_type} wants.")}</pre>
<p>Remember what I said about Procs just being standard Ruby  Objects? Here we are setting the Proc to a variable complaint. We will not raise the Exception unless someone calls this Proc.</p>
<pre name="code" class="ruby">   types_i_know.find(complaint) { |person, value| person.is_a?(Object.const_for(person))}.last</pre>
<p>Lots of Ruby shorthand going on here. We want to look for the String representing what a person wants, so we want to go through the Hash values and return the first value for which the conditional in the block returns true. To do this, we use the following:</p>
<pre name="code" class="ruby">find(value) { |i| condition_with_i }</pre>
<p>Find iterates over the contents of the Enumerable, returning the first Object which fulfils the conditions set forth. If no conditions match, &#8216;value&#8217; is returned. Thus, the code:</p>
<pre name="code" class="ruby">array = [1, 2, 3]
array.find(100){ |i| i % 2 =0}</pre>
<p>returns 2, and the code:</p>
<pre name="code" class="ruby">array = [1, 2, 3]
array.find(100){ |i| i % 4 =0}</pre>
<p>returns 100.</p>
<p>Object.const_for(:symbol) takes a symbol and returns a class. The code:</p>
<pre name="code" class="ruby">User.find(:all)</pre>
<p>could be written as:<br />
type = &#8216;User&#8217;<br />
Object.const_for(type.to_sym).find(:all)</p>
<p>Why would you want to do this? I use this almost all the time in my Rake tasks, especially if I don&#8217;t know what types of classes I will be dealing with, or if I need to read a Class name from the command line.</p>
<pre name="code" class="ruby">person.is_a?(Class)</pre>
<p>This is a very handy method. This will return true if person is an instance of the Class or one of a subclass of Class.</p>
<p>Enough beating around the bush. Let&#8217;s call some code!</p>
<pre name="code" class="ruby"> lion = Lion.new
 jt = JustinTimberlake.new
wants?(lion)</pre>
<pre>=&gt; 'Courage'</pre>
<pre name="code" class="ruby">
wants?(jt)</pre>
<pre>=&gt; ArgumentError: I don't know what JustinTimberlake wants.</pre>
<p>Wow! What did we just do here? We passed an instance of an Object to a wants? method, which in turn delegated the logic to Enumerable&#8217;s find method, returning a Proc Object throwing an Exception if we couldn&#8217;t find what the Person wanted - deferred unless no Object was actually returned by find. How insane is that?</p>
<p>Now go out there and write some Ruby.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/08/30/ruby-procs-part-i/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Rails Controller inheritance and Modules</title>
		<link>http://blog.nuclearpanda.com/2007/08/28/rails-controller-inheritance-and-modules/</link>
		<comments>http://blog.nuclearpanda.com/2007/08/28/rails-controller-inheritance-and-modules/#comments</comments>
		<pubDate>Tue, 28 Aug 2007 22:10:46 +0000</pubDate>
		<dc:creator>Ikai Lan</dc:creator>
		
		<category><![CDATA[ActionController]]></category>

		<category><![CDATA[Object-Oriented Programming]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=9</guid>
		<description><![CDATA[The topic of Controller inheritance may be straightforward for more advanced developers, but it isn&#8217;t completely straightforward for people new to Rails or the Ruby language in general.
Rails Controllers generally come in the following flavor:
 class SomeController &#60; ApplicationController
      some_declarations_here

 def public_method
 end

 private

 def private_method
 end

 end
The Rails Controller [...]]]></description>
			<content:encoded><![CDATA[<p>The topic of Controller inheritance may be straightforward for more advanced developers, but it isn&#8217;t completely straightforward for people new to Rails or the Ruby language in general.</p>
<p>Rails Controllers generally come in the following flavor:</p>
<pre> class SomeController &lt; ApplicationController
      some_declarations_here

 def public_method
 end

 private

 def private_method
 end

 end</pre>
<p>The Rails Controller inherits from a superclass, ApplicationController, which can be found in the app/controllers/application_controller.rb file. Anyone that is familiar with Object Oriented Programming knows, thus, that any method defined in ApplicationController is available in its subclasses. Take the following ApplicationController definition:</p>
<pre>class ApplicationController &lt; ActionController::Base
   def dance
   end
end</pre>
<p>Now we can access the method ApplicationController#dance in SomeController by way of the URI /some/dance. We can actually this this one step further:</p>
<pre>class ApplicationController &lt; ActionController::Base
   layout 'fancy_pickle'
   around_filter :check_for_fanciness

   def dance
   end

   protected

   def check_for_fanciness
      if session[:fancy]
         yield
      else
         render(:text =&gt; 'You are not fancy enough'
      end
   end
end</pre>
<p>What did we just do here? With a few simple and powerful lines of code, we&#8217;ve done all of the following:</p>
<ol>
<li>We&#8217;ve defined a universal default layout for all the controllers in our application. The best part about this is that nothing is set in stone. We can easily override this in a sub controller with the definition:
<pre>layout 'fancier_pickle'</pre>
</li>
<li>We&#8217;ve defined an &#8216;around_filter&#8217; that gets executed before ALL public actions in ALL controllers. This is very useful for almost any application requiring some kind of authentication or authorization matrix. The &#8216;yield&#8217; statement is where the method being called is executed. In my example, if the session variable :fancy is set, that is the only way these methods would execute.</li>
</ol>
<p>Let&#8217;s apply this into practice by defining two more controllers:</p>
<pre> class OtherController &lt; ApplicationController

 def sing
 end

 end</pre>
<pre> class AnotherController &lt; ApplicationController
     def yodel
     end</pre>
<pre> end</pre>
<p>What have we done? We&#8217;ve defined 2 more controllers that inherit from ApplicationController. That&#8217;s right, our Application now has methods at the following URIs:</p>
<pre>/some/dance
/some/public_method
/other/sing
/other/dance
/another/yodel
/another/dance</pre>
<p>All of which are wrapped in a &#8216;check_for_fanciness&#8217; around filter.</p>
<p>Let&#8217;s add one more level of complexity to our project. Suppose we need a method, &#8216;drink_water&#8217;, in our controllers which Yodel and Sing. One way we could do this would be to define it in ApplicationController, in accordance with DRY principles:</p>
<p><font color="#ff0000">BAD!! BAD!!! </font></p>
<pre>class ApplicationController &lt; ActionController::Base
   layout 'fancy_pickle'
   around_filter :check_for_fanciness

   def dance
   end

   def drink_water
   end

   protected

   def check_for_fanciness
      if session[:fancy]
         yield
      else
         render(:text =&gt; 'You are not fancy enough'
      end
   end
end</pre>
<p>While this will work, this is horrible style for at least two reasons. First, the method &#8216;drink_water&#8217; will be available in SomeController, which does not have a Sing or Yodel method. Secondly, any future controllers we define will automatically inherit the method whether they should or not. How do we resolve this issue?</p>
<p>Enter Modules. In C++, we would use multiple inheritance. In Java, we would probably use some combination of Interfaces and Object aggregation. In Ruby, because Ruby is a weakly typed language (officially called &#8216;Duct Typing&#8221; - I&#8217;ll probably write about this in a future post), we would import a Module. It&#8217;s interesting, actually, that Ruby, which touts itself as such an Object Oriented language, would have a feature like this. For those developers familiar with PHP, this is basically the same thing as defining a bunch of methods in a file and then calling &#8216;require&#8217; on the file. But - I digress. Let&#8217;s solve our problem at hand:</p>
<pre>module DrinkMethods
   def drink_water</pre>
<pre>   end
end</pre>
<p>This defines our Module. Let&#8217;s save it as drink_methods.rb, in /app/controllers, for simplicity&#8217;s sake - but for future reference it probably does not belong in that directly.</p>
<p>Now let&#8217;s modify our Controllers that need this method:</p>
<pre> require 'drink_methods'
 class OtherController &lt; ApplicationController
 import DrinkMethods
 def sing
 end

 end</pre>
<pre>require 'drink_methods'
class AnotherController &lt; ApplicationController
     import DrinkMethods
     def yodel
     end</pre>
<pre> end</pre>
<p>Voila! Now we have access to the following URIs without introducing unnecessary inheritances:</p>
<pre>/other/drink_water
/another/drink_water</pre>
<p>Now get out there and write some Ruby.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/08/28/rails-controller-inheritance-and-modules/feed/</wfw:commentRss>
		</item>
		<item>
		<title>has_many :finder_sql</title>
		<link>http://blog.nuclearpanda.com/2007/08/27/has_many-finder_sql/</link>
		<comments>http://blog.nuclearpanda.com/2007/08/27/has_many-finder_sql/#comments</comments>
		<pubDate>Mon, 27 Aug 2007 21:06:55 +0000</pubDate>
		<dc:creator>Ikai Lan</dc:creator>
		
		<category><![CDATA[ActiveRecord]]></category>

		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://nuclearpanda.com/blog/?p=8</guid>
		<description><![CDATA[SQL can be a beautiful thing. That being said, I do try to avoid using native SQL as much as possible when writing applications, because for non-DBA types, it really doesn&#8217;t have the most readable syntax in the world.
In ActiveRecord Models, I make heavy use of Models to represent Join tables - this isn&#8217;t necessary [...]]]></description>
			<content:encoded><![CDATA[<p>SQL can be a beautiful thing. That being said, I do try to avoid using native SQL as much as possible when writing applications, because for non-DBA types, it really doesn&#8217;t have the most readable syntax in the world.</p>
<p>In ActiveRecord Models, I make heavy use of Models to represent Join tables - this isn&#8217;t necessary because of the has_and_belongs_to_many association, however, has_and_belongs_to_many can be very problematic to create Observers for (especially with the limited capabilities of the :after/before_add/remove set of callbacks). In most cases, a HABTM relationship can be defined using only has_many relationships and the :through parameter. Take, for instance, the following representation:</p>
<pre> class ZooTycoon &lt; ActiveRecord::Base
end</pre>
<p>Let&#8217;s think of the relationships here - a ZooTycoon owns many Zoos, which themselves contain Cages, which have Animals which belong in the cage. Using a minimalist approach, how do we attack this problem such that we can build logical relationships between the different classes? We&#8217;d probably do something like this:</p>
<pre> class ZooTycoon &lt; ActiveRecord::Base
	has_many :zoos
 end
 class Zoo &lt; ActiveRecord::Base
        belongs_to :zoo_tycoon
	has_many :cages
 end
class Cage &lt; ActiveRecord::Base
	has_many :animals
	belongs_to :zoo
 end
class Animal &lt; ActiveRecord::Base
	belongs_to :cage
 end</pre>
<p>Humanitarian concerns aside, this is more or less an accurate representation of how the classes are represented. Now, in our application, we can do the following to find out all the animals a particular ZooTycoon owns:</p>
<pre>joey = ZooTycoon.find_by_name('Joey')
zoos = joey.zoos
cages = zoos.collect {|zoo| zoo.cages}
animals =  (cages.flatten.each {|cage| cage.animals }).flatten</pre>
<p>Bear with me, I know there are about a million ways to shorthand this code. What a freakin&#8217; pain! Luckily, we can use the has_many :through association to make this a bit simpler. Let&#8217;s redefine zoos to be able to retrieve animals directly, rather than having to iterate through all the cages:</p>
<pre> class Zoo  :cages,
                       :source =&gt; :animals
 end</pre>
<p>What does this tell our application? It tells us that we don&#8217;t need to create a join table between Zoos and Animals; we already have one! The Cages. We can effectively call the following:</p>
<pre>joeys_zoos.animals</pre>
<p>Yeah, this is nice, but what if we wanted to directly find out all the animals Joey owned? Well, naturally we&#8217;d assume we could do this:</p>
<p><font color="#ff0000">DOES NOT WORK:</font></p>
<pre> class ZooTycoon &lt; ActiveRecord::Base
	has_many :zoos
        has_many :animals, :through =&gt; :zoos
 end</pre>
<p>It breaks. ActiveRecord is pretty smart, but ActiveRecord isn&#8217;t smart enough to correctly create 3 JOINs. If we take a look at the log, we realize that ActiveRecord is trying to directly join the ZooTycoon with the Zoo with the Animals, bypassing the Cages completely. What do we do? Looks like finder_sql to the rescue. SQL can be ugly, but SQL can also be a beautiful thing when you need something very specific:</p>
<pre> class ZooTycoon  'Animal',
                       :finder_sql = 'SELECT * FROM zoo_tycoons
                                           JOIN zoos ON zoo_tycoons.id = zoos.zoo_tycoon_id
                                           JOIN cages ON zoos.id = cages.zoo_id
                                           JOIN animals ON animals.cage_id = cages.id
                                           WHERE zoo_tycoon.id = #{id}'

  end</pre>
<p>NOTE THE SINGLE QUOTES. <b>Note the single quotes. </b><i>Note the single quotes.</i><b> </b>You MUST use single quotes. To understand why this is, you have to understand that the &#8216;configuration&#8217; methods in ActiveRecord models are actually function calls that get executed before any Models are actually instantiated. Finder_sql is effectively a function that goes something like, set_some_value_to(&#8217;#{self.id}&#8217;) that gets called before any Objects are created, so the instance variable @some_value is set to &#8216;#{self.id}&#8217; rathern than the Object id of the class, which will probably be some ridiculous 11 digit number rather than the Model&#8217;s ID. By passing a single quoted parameter, we ensure that the #{id} value substitution happens during an Object&#8217;s lifecycle.</p>
<p>What does this mean for us? We can now call:</p>
<pre>joey.animals</pre>
<p>What&#8217;s totally awesome about this is that now we get the entire suite of ActiveRecord methods and callbacks for free! What if Joey wants his animals to be destroyed when he is destroyed? We just append a :dependent =&gt; :destroy.</p>
<p>Now go out there and write some Ruby.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nuclearpanda.com/2007/08/27/has_many-finder_sql/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
