<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>Shedding Light on Ruby</title>
	<atom:link href="http://evan.tiggerpalace.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://evan.tiggerpalace.com</link>
	<description>Spreading the gospel</description>
	<pubDate>Sun, 29 Jun 2008 13:58:24 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>Stone Soup</title>
		<link>http://evan.tiggerpalace.com/2008/06/25/stone-soup/</link>
		<comments>http://evan.tiggerpalace.com/2008/06/25/stone-soup/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 00:17:51 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/06/25/stone-soup/</guid>
		<description><![CDATA[I&#8217;ve been to a lot of Ruby conferences this past year.  Yet the more that I attend, the more that they seem the same.  I see the same people giving the same presentations on the same topics.  Sure, they add some content here, drop a slide there, or maybe add a different [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been to a lot of Ruby conferences this past year.  Yet the more that I attend, the more that they seem the same.  I see the same people giving the same presentations on the same topics.  Sure, they add some content here, drop a slide there, or maybe add a different spin on the same subject as before.  But, at the end of the conference, I find myself asking &#8220;What makes this conference different than any other conference?&#8221;  There are more people?  There are less people?  It&#8217;s someplace different?  That&#8217;s often all that I can say.</p>

<p>At RailsConf, Chad Fowler opened and offered one observation that I found particularly profound.  He admitted that he doesn&#8217;t do particularly well in a classroom setting &#8212; and implied that conference talks are like a classroom environment.</p>

<p>That struck me to the core.  That&#8217;s me.</p>

<p>At Ruby conferences, I see few people voting with their feet.  However, I see many people who barely pay attention to the speaker.  Instead, they are on IRC discussing how disappointed they are in the speaker, writing a Rails app or Ruby gem, or just surfing the net.</p>

<p>So why even go to the talks at conferences?  Why have the talks?  Obviously, most Ruby conference attendees  would rather be doing something on or computer, social or otherwise.</p>

<p>Beteween games of Werewolf at Ruby East last year (<a href="http://headius.blogspot.com/2007/11/is-werewolf-killing-conference-hackfest.html">my humble apologies to Charlie Nutter</a>), <a href="http://gilesbowkett.blogspot.com/">Giles</a> and I were yakking away.  Somewhat randomly, he says something like, &#8220;Man, you and I&#8230; we&#8217;re just scenesters.&#8221;</p>

<p>That&#8217;s exactly what I&#8217;d become.  I didn&#8217;t realize it until that moment.  That had never ever been me but it sure is now.  And I bet that&#8217;s you too.</p>

<p>You go for the scenius.</p>

<p>That&#8217;s a Brian Eno-ism.  It&#8217;s &#8220;the emergent genius of a colocated culture&#8221;.  It&#8217;s that spark you get, that inspiration, that makes you feel <strong>smarter</strong> just because you&#8217;re working near and talking with the poeple that you are where you are.</p>

<p>I don&#8217;t see much exchange when there is a talking head, even a brilliant one, at the front of the room with an audience full of mostly silent people.  Why is a group of such seemingly independently-minded people as the Ruby community willingly enslaving themselves to the words of one person after another for 45 minutes a pop?  Just how educational does this really turn out to be?</p>

<p>&#8220;This town needs an enema&#8221; - The Joker, Batman (1990)
<img style="float: right" src="http://evan.tiggerpalace.com/wp-content/uploads/2008/06/image.jpg" /></p>

<p>Why should Ruby conferences be traditional conferences?  Just because everyone else does it that way?  Odd.  I don&#8217;t see this community (communities?) as followers.  </p>

<p><a href="http://gilesbowkett.blogspot.com/2008/06/fear-and-loathing-at-railsconf.html">Giles</a> asserts that we&#8217;re a weird bunch of people</a>.  Hell, I thrive on it &#8212; just as much as I gag on the lack of weird when I return to my day job from a conference.</p>

<p>So why not just be <strong><em>weird</em></strong> instead of being like every other conference out there with their clearly delineated speakers, audiences, and Nascar-like corporate branding?</p>

<p>No I don&#8217;t mean Ruby Fringe (although I am going).</p>

<p>Let&#8217;s invert the process.  More discussion.  More hacking.  Less talking heads.</p>

<p>Let&#8217;s make some awesome <a href="http://en.wikipedia.org/wiki/Stone_soup">Stone Soup</a>.</p>

<p>I&#8217;ve discussed this with some people around the community.  The often conservative and stodgy DC Metropolitan Area may hold the first Ruby BarCamp.  Does someone want to beat us to the punch?  I triple-dog dare you.</p>

<p><b>Update 6/29/08: <a href="http://smartic.us/">Bryan Liles</a> pointed me at <a href="http://www.scripting.com/stories/2008/06/22/rethinkingTheConference.html">an article by Dave Winer about the &#8220;early days&#8221; of unconferences</a>.  His timing is serendipitous.  Come on, people!  Let&#8217;s make something happen!</b></p>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/06/25/stone-soup/feed/</wfw:commentRss>
		</item>
		<item>
		<title>NoVaJUG presentation of Unit Testing J2EE from JRuby</title>
		<link>http://evan.tiggerpalace.com/2008/06/24/novajug-presentation-of-unit-testing-j2ee-from-jruby/</link>
		<comments>http://evan.tiggerpalace.com/2008/06/24/novajug-presentation-of-unit-testing-j2ee-from-jruby/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 23:12:13 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

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

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/06/24/novajug-presentation-of-unit-testing-j2ee-from-jruby/</guid>
		<description><![CDATA[This evening, I gave my first presentation of Unit Testing J2EE from JRuby to the Northern Virginia Java User&#8217;s Group.  It was a very interesting experience.  The audience asked some interesting questions &#8212; but it was also an insightful reminder of my origins as an engineer.  Out of approxiately a 30 member [...]]]></description>
			<content:encoded><![CDATA[<p>This evening, I gave my first presentation of Unit Testing J2EE from JRuby to the Northern Virginia Java User&#8217;s Group.  It was a very interesting experience.  The audience asked some interesting questions &#8212; but it was also an insightful reminder of my origins as an engineer.  Out of approxiately a 30 member audience, perhaps 4 had done any TDD and only a single one had ever used mock objects.  While mocks have their origins largely in Java (at least their initial implementations), it is interesting to see that they have been far more readily adopted in the Ruby community than Java.</p>

<p>Also, Mocha suddenly jumped from v0.5.6 to v0.9?!</p>

<p><img src='http://evan.tiggerpalace.com/wp-content/uploads/2008/06/omgwtfrubikscube-1.jpg' /></p>

<p>So jrsplenda broke when I tried to demo it on my wife&#8217;s spiffy new Macbook Air &#8212; as I was foolish enough to just &#8217;sudo gem install mocha&#8217;.  </p>

<p>Who the hell has a public release at 0.5.6 and then another at 0.9?  I am so integrating FlexMock into jrsplenda in the next release.  I can&#8217;t see <a href="http://onestepback.org/">Jim Weirich</a> doing anything like that.</p>

<p>I&#8217;m halfway tempted to redo and give my <a href="http://evan.tiggerpalace.com/files/BDD%20with%20RSpec.pdf">BDD with RSpec</a> talk to NoVaJUG as a JRuby-Java BDD talk.  More people should be doing BDD and not merely those of us working in dynamic languages.  Were it so, I imagine that I would encounter far more testable and maintainable code in the Java community.</p>

<p>Slides from the presentation are available <a href="http://evan.tiggerpalace.com/wp-content/uploads/2008/06/unit-testing-jruby-from-java-public.pdf">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/06/24/novajug-presentation-of-unit-testing-j2ee-from-jruby/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Presenting at ERubycon in August</title>
		<link>http://evan.tiggerpalace.com/2008/06/02/presenting-at-erubycon-in-august/</link>
		<comments>http://evan.tiggerpalace.com/2008/06/02/presenting-at-erubycon-in-august/#comments</comments>
		<pubDate>Tue, 03 Jun 2008 05:36:30 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/06/03/presenting-at-erubycon-in-august/</guid>
		<description><![CDATA[I&#8217;m extremely excited to announce that ERubycon has accepted my proposal to speak on JRuby testing of JEE.  ERubycon is unique in that it is expressly focused on Ruby in the Enterprise.  While &#8220;enterprise&#8221; is a squishy term to me (my take on it is &#8220;legacy/internal facing/business-to-business/large scale development&#8221;), I suspect that the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m extremely excited to announce that <a href="http://erubycon.com/">ERubycon</a> has accepted my proposal to speak on JRuby testing of JEE.  ERubycon is unique in that it is expressly focused on Ruby in the Enterprise.  While &#8220;enterprise&#8221; is a squishy term to me (my take on it is &#8220;legacy/internal facing/business-to-business/large scale development&#8221;), I suspect that the constituency will be somewhat different than the other Ruby conferences that I&#8217;ve attended this past year (i.e., RailsConf, RubyConf, Ruby Hoedown, and Ruby East).  As the majority of my work falls clearly into the enterprise space, I&#8217;m looking forward to ERubycon.</p>

<p>ERubycon is August 15-17 in Columbus, Ohio.  I hope to see you there.</p>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/06/02/presenting-at-erubycon-in-august/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Improving Java unit testing and introducing jrsplenda v0.1.1</title>
		<link>http://evan.tiggerpalace.com/2008/06/01/improving-java-unit-testing-and-introducing-jrsplenda-v011/</link>
		<comments>http://evan.tiggerpalace.com/2008/06/01/improving-java-unit-testing-and-introducing-jrsplenda-v011/#comments</comments>
		<pubDate>Sun, 01 Jun 2008 13:07:40 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/06/03/improving-java-unit-testing-and-introducing-jrsplenda-v011/</guid>
		<description><![CDATA[Last week, I wrote about the pain of Java unit testing.  At the end of it all, I said that I would supply some answers &#8220;tomorrow&#8221;.

One week and one RailsConf later, I&#8217;ll call this &#8220;tomorrow&#8221;.

In the previous article, I listed a handful of commons Java idioms that reduce testability.  Three out of four [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, <a href="http://evan.tiggerpalace.com/2008/05/25/the-agony-of-java-unit-testing/">I wrote about the pain of Java unit testing</a>.  At the end of it all, I said that I would supply some answers &#8220;tomorrow&#8221;.</p>

<p>One week and one RailsConf later, I&#8217;ll call this &#8220;tomorrow&#8221;.</p>

<p>In the previous article, I listed a handful of commons Java idioms that reduce testability.  Three out of four of the issues may be rolled up into a higher level of abstraction: <strong>encapsulation kills</strong>.  The remaining point may be summarized as <strong>Spring XML == code that most developers don&#8217;t test</strong>.  Encapsulation prevents developers from injecting mock objects into their code.  Without mocks, the unit under test lacks isolation.  Without isolation, your unit test is an integration test at best and a massive FAIL at worse.</p>

<p>If you endured a Computer Science curriculum in college, I&#8217;m reasonably sure that the professor of your second or third CS class repeatedly hammered home: encapsulation is a key tenet of good object-oriented design.  However, many dynamic languages only provide a brief nod, if any, to the encapsulation gods.  For instance, Python does not support private or protected members.  While Ruby does, it is trivial to route around those protections.  What some may not realize is that, in this respect, Java is little different than Ruby.</p>

<p>Yes, that&#8217;s right.  Java can be a bit on the promiscuous side of things too.</p>

<p><span id="more-56"></span></p>

<p>I&#8217;m not sure what you&#8217;re &#8220;java.policy&#8221; file allows in your Java installation but, on OS X, the default allows for Java reflection to route around field and method access privileges.  Don&#8217;t believe me?  Take a gander at the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/AccessibleObject.html"><code>java.lang.reflect.AccessibleObject</code></a> class that is the parent of Field, Method, and Constructor reflection objects.</p>

<p>With this, you could write/generate a lot of code to act as wrappers for Java objects to expose private, protected, and package scoped Fields, Methods, and Constructors.  While this is somewhat interesting, we can do better.</p>

<p>So why bother using Spring for object creation and dependency injection?  No, seriously, think about it.  Do you test your Spring XML?  I would bet every Java developer who reads this article that, as of the authoring date, that you don&#8217;t.  Ruby is <strong>extremely</strong> testable.  So why are you writing all of that glue code in XML and not testing it?  Write it in a Turing Complete programming language and test it, for crying out loud!</p>

<p>But I digress (however only slightly)&#8230;</p>

<p>Ruby excels at DSL creation.  This has been demonstrated with awesome effect in the unit testing/specifciation domain.  But did you know that Ruby&#8217;s testing and specification DSLs (i.e., RSpec) can be used to test Java?  Oh, yes, it&#8217;s true.  And Ruby&#8217;s mocking libraries (i.e., Mocha, Flexmock, and RSpec mocking), with their ability to create mocks at runtime with just a line of code simply blow Java away.</p>

<p>So what if we put our chocolate in our peanut butter?  JRuby, as of v1.1.2, provides workable Java integration such that a JRuby mock object, generated by <a href=" http://mocha.rubyforge.org/">Mocha</a>, may be injected into a Java object instantiated in JRuby.</p>

<p>Next we write some java.lang.reflect calls, in JRuby (!!), to wrap each non-public field and method for a given Java object with a JRuby method.  Yes, a JRuby method.  The generated JRuby method takes advantage of the <code>java.lang.reflect.AccessibleObject</code>&#8217;s features to provide setters (JRuby already provides getters) for Fields and to provide direct access to Methods.</p>

<p>Now we can inject these JRuby-created mocks from Test::Unit or RSPec into almost any part (well, ok, except for final members and local variables) of our Java objects.  Suddenly, we&#8217;re writing test code that&#8217;s a whole lot more readable and we&#8217;re writing a lot less of it!</p>

<h2>Splenda</h2>

<p><img src="http://evan.tiggerpalace.com/files/splenda.jpg" style="float: right; height: 250px; width: 188px" /></p>

<p>I call the field and method wrappers &#8220;Splenda&#8221; or <a href="https://github.com/elight/jrsplenda/tree">&#8220;jrsplenda&#8221;</a> for JRuby Splenda &#8212; to sweeten up Mocha.  While there are still some minor limitations as of v0.1.1 (see the README provided in the <a href="http://github.com/elight/jrsplenda/tree/master">github project</a>), I&#8217;ve already re-written some of the JRuby RSpec from my current project to use Splenda.  It works like a champ.</p>

<p>Working sample code has been supplied with jrsplenda in the github project.  Nonetheless, it bears mentioning describing it in brief.</p>

<p>Splenda is made up of three helper modules: a MockHelper, FieldHelper, and MethodHelper.  </p>

<h1>MockHelper</h1>

<p>The MockHelper, predictably, supplies mock objects but also provides a facility for generating a mock of a Java class and storing the mock in a member attr named after the Java class </p>

<p>Example
<pre>
  # inside a spec or test....
  require 'rubygems'
  require 'jrsplenda'</p>

<p>include JRSplenda::MockHelper</p>

<p>splenda<em>mock</em>attr &#8216;javax.ejb.SessionContext&#8217;</p>

<p># => Creates a @session_context containing a mock for a SessionContext in one line
</pre></p>

<h1>FieldHelper</h1>

<p>The FieldHelper wraps all non-public (and non-final) fields for a given Java object.  This is awfully handy for injecting your mocks.</p>

<p>Example
<pre>
  #inside a spec or test
  require 'rubygems'
  require 'jrsplenda'</p>

<p>include JRSplenda::FieldHelper</p>

<p>import &#8216;my.fake.TestClass&#8217;</p>

<p>t = TestClass.new
  wrap<em>java</em>fields t</p>

<p># => Generates setters for all non-public non-final fields of the TestClass instance pointed to by t
</pre></p>

<h1>MethodHelper</h1>

<p>The MethodHelper wraps all non-public methods for a given Java object.  This one is nice for white box testing of internal methods.</p>

<p>Example
<pre>
  #inside a spec or test
  require 'rubygems'
  require 'jrsplenda'</p>

<p>include JRSplenda::MethodHelper</p>

<p>import &#8216;my.fake.TestClass&#8217;</p>

<p>t = TestClass.new
  wrap<em>java</em>methods t</p>

<p># => Generates setters for all non-public non-final fields of the TestClass instance pointed to by t
</pre></p>

<h1>Take away</h1>

<ol>
<li>Java may work in isolation but it is better still with the assistance of a dynamic language</li>
<li>JRuby, as of v1.1.2, can integrate well with Java</li>
<li>JRuby + RSpec can test Java code</li>
<li>Mocha + Splenda make this not only ridiculously easy but ridiculously readable</li>
<li>Question whether you really need Spring.  Dynamic languages running in the Java VM can accommodate your dependency injection needs; they&#8217;re far more testable than your Spring XML</li>
</ol>

<p><a href="http://github.com/elight/jrsplenda/tree/master">The latest version is available on github</a>.  Clone the repository and &#8216;rake install_gem&#8217; to get the gem.</p>

<p>Oh, and Splenda may cause diarhea and bloating.  Just sayin&#8217;.</p>

<p><em>Update: Incidentally, Flexmock actually plays very nicely with JRuby.  I&#8217;ll be adding support for it in Splenda in the next release.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/06/01/improving-java-unit-testing-and-introducing-jrsplenda-v011/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The agony of Java unit testing</title>
		<link>http://evan.tiggerpalace.com/2008/05/25/the-agony-of-java-unit-testing/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/25/the-agony-of-java-unit-testing/#comments</comments>
		<pubDate>Sun, 25 May 2008 23:05:47 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[DO NOT WANT]]></category>

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/26/the-agony-of-java-unit-testing/</guid>
		<description><![CDATA[Java unit testing sucks!!!

There, I said it.

Come on, it does.  I know, 8 years ago, JUnit was the bees knees.  But let&#8217;s face it: when you&#8217;re working on a project, you&#8217;re behind schedule for whatever reason, and you have a deadline looming, where&#8217;s the first place that you cut corners?

Unit tests.  Always.

Why?


Lack [...]]]></description>
			<content:encoded><![CDATA[<p>Java unit testing <em><em>sucks</em></em>!!!</p>

<p>There, I said it.</p>

<p>Come on, it does.  I know, 8 years ago, JUnit was the bees knees.  But let&#8217;s face it: when you&#8217;re working on a project, you&#8217;re behind schedule for whatever reason, and you have a deadline looming, where&#8217;s the first place that you cut corners?</p>

<p>Unit tests.  Always.</p>

<p>Why?</p>

<ol>
<li>Lack of perceived value of testing (in other words: I see the <em>happy path</em> works so what&#8217;s your big problem?)</li>
<li>No one is going to ever touch this code again after this release</li>
<li>Java is just difficult to test</li>
</ol>

<p>Let&#8217;s talk about these&#8230;.</p>

<p><span id="more-55"></span></p>

<h1>Why You Don&#8217;t Test (a.k.a., why you&#8217;re brain damaged)</h1>

<p><strong>Lack of perceived value of testing</strong></p>

<p>If that&#8217;s the way you feel, then you shouldn&#8217;t <em>ever</em> call yourself an engineer.  You&#8217;re just a hack.  Still, I&#8217;ll assume that there&#8217;s hope for you yet because you&#8217;re reading this article in the first place.</p>

<p><strong>The <a href="http://nostalgia.wikipedia.org/wiki/SEP_field">&#8220;Somebody Else&#8217;s Problem&#8221;</a> Field</strong></p>

<p>You&#8217;re leaving the project soon.  Or you honestly believe that your shit doesn&#8217;t stink.  Or you&#8217;re just going to leave it for the next guy.  It&#8217;s <em>somebody else&#8217;s problem</em>.  There&#8217;s one response to this: in this business, frequently, that somebody is you.  If you can&#8217;t maintain your own code then you&#8217;ve just shot yourself in the foot.  Congratulations.</p>

<p><strong>But, now, to the heart of the matter.</strong></p>

<p><strong>Java is just difficult to test</strong>
Now I know that <a href="http://blog.thinkrelevance.com/2008/5/18/java-is-naturally-untestable">I&#8217;m not the first one to say this</a>.  However, in my opinion, what makes difficult to test are the idioms and practices that developers have acquired over the 13 years that Java has been around.  Many of these idioms and practices fly almost completely counter to testing &#8212; <strong>for in order to be able to test effectively, we must be able to isolate the unit under test</strong>.  How do we do this in Java?  Dependency injection.  Come on, you knew I was going to say that, right?  </p>

<h1>Evil/Brain-Damaged/Detrimental Idioms/Practices</h1>

<ul>
<li><em>Enterprise Java Beans</em>.  Come on, already.  <em>Private variables</em> mutated by the container based on an XML deployment descriptor (so we&#8217;re coding in XML now )?  Are you testing your deployment descriptor?  You probably should be.  Have I ever done it.  Not yet&#8230;.</li>
<li><em>Spring</em>.  Yes, POJOs are good.  Actually, I&#8217;ll amend that.  POJOs are <strong>fucking awesome</strong> &#8212; especially when every member variable is exposed via a getter and a setter.  Unfortunately, you&#8217;re now effectively writing code in XML.  So are you going to write tests just to exercise your XML?  If you aren&#8217;t, you should be.  That XML creates and links objects together.  As soon as you start coupling things dynamically, you have a relationship that could break and therefore warrants testing.</li>
<li><em>private/protected member variables</em>.  We need these, don&#8217;t we?  Sometimes, yes, actually, we do.  However, if they aren&#8217;t wrapped (see Spring above) then Houston we have a problem.</li>
<li><code>static final</code> used for non-primtive/String constants.  This is simply <em>everywhere</em> in the Java universe: developers statically initializing constants with Objects.  This is <strong>awful</strong>.  Why, you ask?  Because how the hell are you ever going to be able to inject a value for that static final Object?  It&#8217;s assigned at classloading time.  So, basically, grab your ankles and <a href="http://www.urbandictionary.com/define.php?term=B.O.H.I.C.A">BOHICA</a>.</li>
</ul>

<p>Unfortunately&#8230;</p>

<ul>
<li>Some of these hurtful practices are necessary

<ul>
<li>Encapsulation</li>
<li>Spring XML (if you&#8217;re stuck coding Java in the first place)</li>
</ul></li>
<li>Sometimes we&#8217;re working in legacy code

<ul>
<li>Limited ability to change existing code; stuck with bad practices</li>
<li>Existing unit tests are sometimes lacking</li>
</ul></li>
</ul>

<p><strong>How do we get better?</strong></p>

<p>Come back tomorrow.  We&#8217;ll talk.  Seriously.</p>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/25/the-agony-of-java-unit-testing/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Avanced Ruby Studio, Day 3</title>
		<link>http://evan.tiggerpalace.com/2008/05/09/avanced-ruby-studio-day-3/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/09/avanced-ruby-studio-day-3/#comments</comments>
		<pubDate>Sat, 10 May 2008 06:41:45 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/10/avanced-ruby-studio-day-3/</guid>
		<description><![CDATA[Notes after the jump.  

Aside: They brew insanely strong coffee at the Sheraton&#8230;



Domain Specific Language


Discussions comparing DSLs to expressive DSLs


Me: I don&#8217;t believe that there&#8217;s a difference but Ruby brings us closer to English in our DSLs
DT: Which causes a whole new level of confusion because while it reads easily it&#8217;s hard to write
DSLs, [...]]]></description>
			<content:encoded><![CDATA[<p>Notes after the jump.  </p>

<p>Aside: They brew insanely strong coffee at the Sheraton&#8230;</p>

<p><span id="more-53"></span></p>

<h2>Domain Specific Language</h2>

<ul>
<li>Discussions comparing DSLs to expressive DSLs

<ul>
<li>Me: I don&#8217;t believe that there&#8217;s a difference but Ruby brings us closer to English in our DSLs</li>
<li>DT: Which causes a whole new level of confusion because while it reads easily it&#8217;s hard to write</li>
<li>DSLs, to him, represent a domain-specific form of abstraction</li>
</ul></li>
<li>Rake

<ul>
<li>CF: Dependency-oriented DSL</li>
<li>Me: Now that is a nifty abstraction to capture the purpose of Rake</li>
</ul></li>
<li>Dhaka</li>
<li><p>JDWP DSL
CF: cites an example of a Java Debugger Wire Protocol implementation that Rich Kilmer wrote by copying the documentation into a Ruby file and simply reformatting the docs into valid Ruby code.</p>

<ul>
<li>Readable to SUN developers</li>
<li>DT: DSL is retargetable &#8212; specifies intent, not implementation</li>
</ul></li>
<li><p>Implementation tricks</p>

<ul>
<li>method_missing</li>
</ul></li>
<li><p>CF: Most DSLs are block based</p></li>
<li>To <code>instance&#95;eval</code> or not to <code>instance&#95;eval</code>

<ul>
<li><code>instance&#95;eval</code> is constraining because it redefines <code>self</code></li>
<li>DT: The DSL is a promise (Me: a contract?  interface&#8230;) that should be consistent</li>
</ul></li>
<li><strong>Consider context: who will use the DSL?</strong></li>
</ul>

<p>This is a good discussion.</p>

<ul>
<li>DSL anti-patterns

<ul>
<li>False familiarity</li>
<li><code>method&#95;missing</code> and <code>respond&#95;to></code> together</li>
<li>If you support one then you should support the other</li>
<li>Cluttering namespaces (flexibility)</li>
</ul></li>
</ul>

<p><strong>break &amp; exercise (write a morse code generator for a given pattern</strong></p>

<pre>
  class MorseEncoder
    CHARS = {
      :a => "._",
      :b => "_...",
      :c => "_._.",
      :d => "_..",
      :e => "."
    }

    def initialize
      @msg = []
    end

    def encode(&#038;block)
      instance_eval(&#038;block).reverse.join(&#8221; &#8220;)
    end

    def method_missing(name, *args)
      @msg << CHARS[name]
    end
  end

  morse = MorseEncoder.new
  puts morse.encode { b e a d }
</pre>

<p>Extremely pleased how much more comfortable I&#8217;ve become with my use of blocks and closures over the period of this class.  This course has provided some good brain strengthening exercises.</p>

<h2>Exotic Control Flow</h2>

<ul>
<li>DT: &#8220;I don&#8217;t know what BASIC is.  The dribbling old fool of programming langauages&#8221;

<ul>
<li>Likens exception handling to &#8220;goto on steroids&#8221;</li>
<li>Implies that goto is not necessarily harmful</li>
<li>It&#8217;s up to the individual programmer</li>
</ul></li>
<li>DT: &#8220;Experts know when to break the rules&#8221;</li>
<li><strong>LOL: Don&#8217;t not use positive logic</strong></li>
<li><p><code>throw</code> and <code>catch</code></p>

<ul>
<li><strong>This is not Java&#8217;s throw/catch &#8212; almost the opposite</strong> (that&#8217;s <code>raise</code> and <code>rescue</code>)</li>
<li><code>catch</code> takes a label and <strong>executes a block</strong></li>
<li><code>throw</code> takes a label and optional arguments</li>
<li>Causes Ruby to unwind the call stack to the first <code>catch</code> that matches

<ul>
<li>The optional parameter is the return value to provide from the catch </li>
</ul></li>
<li>Real use: open-uri</li>
<li>Me: This would elminate <strong>so much code</strong> from my current project in the office &#8212; if they hadn&#8217;t already writen it in Java&#8230;</li>
</ul></li>
<li><p>Continuations</p>

<ul>
<li><code>callcc</code></li>
<li><em>requires</em> a block with <em>one parameter</em> (the conitnuation)</li>
<li><strong>Executes the block</strong></li>
<li>When a continuation is called, execution resumes immediately after the continuation&#8217;s block</li>
<li>All control structures can be implemented via continuations</li>
</ul></li>
</ul>

<p><strong>Lunch and Exercise</strong></p>

<pre>
# Write the methods start_loop and end_loop so that the following does what you'd expect:

i = 0

again = start_loop

puts i
i += 1

end_loop(again) unless i > 5
</pre>

<p>&#8230; which is solved by:
<pre>
def start_loop
  callcc { |cont| cont }
end</p>

<p>def end_loop(continuation)
  continuation.call(continuation)
end
</pre>
&#8230; which was less code than I expected.  Admittedly, I didn&#8217;t know at the time that <code>Continuation#call</code>&#8217;s parameter is returned by <code>callcc</code> but it made sense so I tried it.  Principle of least surprise FTW!</p>

<p>I won a gold star for niftiest continuation implementatio for this exercise.  Yay, me!</p>

<h2>Debugging &amp; Profiling</h2>

<ul>
<li>ruby -d

<ul>
<li>Sets <code>$DEBUG</code></li>
<li><code>caller</code>: call stack, file names, and line numbers (Me: handy stuff!!)</li>
</ul></li>
<li>ruby-debug gem

<ul>
<li>Insert a <code>debugger</code> call into Ruby code to dump into the debugger from the runtime</li>
<li>Also requires requiring the gem (duh)</li>
<li>Inside the debugger, can launch into irb in the current context</li>
</ul></li>
<li><p><strong>gdb</strong></p>

<ul>
<li>Attach to the running Ruby VM</li>
<li><code>gdb gdb&#95;path&#95;to&#95;Ruby&#95;bin Ruby&#95;VM&#95;PID</code></li>
</ul></li>
<li><p>Ruby &#8216;profile&#8217; library</p>

<ul>
<li>Me: Woops, didn&#8217;t know about this library!</li>
<li><code>ruby -r profile my&#95;program&#95;name</code></li>
<li>Profiling specific parts of code</li>
<li><code>Profiler&#95;&#95;::start&#95;profile</code></li>
<li><code>Profiler&#95;&#95;::stop&#95;profile</code></li>
<li><code>Profiler&#95;&#95;::print&#95;profile</code></li>
</ul></li>
<li>Question about memory profiling

<ul>
<li>No known available tools</li>
<li>ObjectSpace &#8212; roll your own</li>
<li>DT: modified <code>new</code> to add a timestamp to every Object to add a timestamp to allow searching for super-stale objects</li>
</ul></li>
<li>Exploring how objects are interacted with

<ul>
<li>Slide 329</li>
<li>Undef all of the methods on an object and then see what errors occur</li>
</ul></li>
</ul>

<h2>JRuby</h2>

<ul>
<li>Java garbage collection</li>
<li>Hotspot</li>
<li>Java threads (native)</li>
<li><code>rake war:standalone:create</code></li>
<li>IronRuby promises Ruby in the browser</li>
</ul>

<h2>Distributed Programming</h2>

<ul>
<li>DRb (Me: cake)</li>
<li>Rinda (<a href="http://evan.tiggerpalace.com/2008/02/25/rinda-or-hardware-is-cheap-so-lets-use-more-of-it/">Me: been there done that</a>)

<ul>
<li>UDP broadcasts</li>
</ul></li>
<li>Custom Protocol Implementation

<ul>
<li>Transport mechanism</li>
<li>Encoding mechanism</li>
</ul></li>
<li>GServer</li>
<li>NetSSH</li>
<li>Slide 396 for Multicast in Ruby

<ul>
<li>IPs 224.0.0.0 to 239.255.255.255 are multicast reserved addresses</li>
</ul></li>
<li>Slide 398 shows a simple proc running on a WEBRick server: 7 lines of code. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </li>
<li>Rack

<ul>
<li>Sits on top of any web server and provides a WEBRick-like API</li>
</ul></li>
<li>open-uri

<ul>
<li>rest-open-uri &#8212; patches open-uri to support other HTTP methods</li>
</ul></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/09/avanced-ruby-studio-day-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Advanced Ruby Studio, Day 2</title>
		<link>http://evan.tiggerpalace.com/2008/05/09/advanced-ruby-studio-day-2/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/09/advanced-ruby-studio-day-2/#comments</comments>
		<pubDate>Fri, 09 May 2008 20:46:09 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/09/advanced-ruby-studio-day-2/</guid>
		<description><![CDATA[This morning session rocked my world.  The afternoon session was better than yesterday but, for me, dragged a lot toward the end of the day.

I suspect that my less enthusiastic response to this class vice the Rails class has more to do with my significantly greater experience with Ruby the language than Rails the [...]]]></description>
			<content:encoded><![CDATA[<p>This morning session rocked my world.  The afternoon session was better than yesterday but, for me, dragged a lot toward the end of the day.</p>

<p>I suspect that my less enthusiastic response to this class vice the Rails class has more to do with my significantly greater experience with Ruby the language than Rails the framework.</p>

<p>That said, I am still finding this class worthwhile to fill in the gaps in my understanding of Ruby to date.</p>

<p>Notes after the jump.</p>

<p><span id="more-52"></span></p>

<h2>Ruby Object Model</h2>

<p>NOTE: Parts of this portion of the class were presented to NoVaRUG in April by DT.</p>

<ul>
<li><code>self</code> is the <strong>only</strong> way to access member variables.</li>
<li>Changing <code>self</code> is key to Ruby

<ul>
<li>On a method call</li>
<li><code>self</code> gets set to the receiver then the method is looked up</li>
<li>When defining a class</li>
<li>This is universal to all implementations of Ruby</li>
</ul></li>
<li>Methods are stored on classes, data in objects.  (Me: Nothing new there but important to note for below)</li>
<li>When defining a method on an instance of a class, Ruby creates an anonymous class (aka &#8220;singleton class&#8221;, &#8220;eigenclass&#8221;, &#8220;virtual class&#8221;, and &#8220;metaclass&#8221;) to contain the new method and has it inherit from the original parent class.</li>
<li><strong>If reader == Java.WEENIE</strong>

<ul>
<li><strong>Ruby classes are executable code</strong></li>
<li><strong>Ruby classes are Ruby Objects</strong></li>
<li>Me: Imagining your brain &#8217;sploding. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </li>
</ul></li>
</ul>

<p><strong>Classes are executable code</strong>
<pre>
puts "foo"</p>

<p>class Stuff
  puts &#8220;bar&#8221;
end</p>

<p>puts &#8220;blech&#8221;
</pre></p>

<p>&#8230; outputs:</p>

<pre>
  foo
  bar
  blech
</pre>

<p><strong>Classes are objects</strong>
<pre>
puts "foo"</p>

<p>class Stuff
  @v = 123
  def self.get_v
    @v
  end
end</p>

<p>puts Stuff.get_v
puts &#8220;bar&#8221;
</pre></p>

<p>&#8230; outputs: </p>

<pre>
  foo
  123
  bar
</pre>

<p><em>Matz says &#8220;don&#8217;t use @@ vars&#8221; and DT agrees.</em></p>

<ul>
<li>Instance variables looked up in <code>self</code></li>
<li><p>Methods looked up in <code>self</code>&#8217;s class</p></li>
<li><p>Method definition is different than method lookup</p>

<ul>
<li><code>def foo</code> is defined in the current class</li>
<li><code>def obj.foo</code> is defined in <code>obj</code>&#8217;s singleton class</li>
</ul></li>
</ul>

<p><strong>And the lightbulb goes off over my head</strong></p>

<p>So this idiom that I&#8217;ve seen Giles use in his code somewhere doesn&#8217;t hurt my brain anymore:</p>

<pre>
  something = "42"
  class << something
    def say_something
      puts self
    end
  end
  something.say_something
</pre>

<p>&#8230; will output <code>42</code>.  <code>class &lt;&lt; something</code> changes the current Class to the singleton class of <code>something</code>.  </p>

<p>Although the below example behaves the same way, it is less explicit in that it obscures what&#8217;s happening under the covers.  The below example seems to define a method on <code>something</code>; it&#8217;s actually defining the method on <code>something</code>&#8217;s singleton class.</p>

<pre>
  something = "42"
  def something.say_something
    puts self
  end
  something.say_something
</pre>

<p>Intrestingly, <code>clone</code> copies a singleton class as well but <code>dup</code> doesn&#8217;t.</p>

<p>Cute but not hugely relevant:</p>

<pre>
  class Person < Struct.new(:name, :state)
    # do stuff
  end
</pre>

<p>&#8230; is legal &#8212; and a nifty way to save lines of code if you want to add methods to a Struct (<strong>or other expression that evals to a Class</strong>).</p>

<ul>
<li><p><code>include</code></p>

<ul>
<li>Points this object&#8217;s singleton class to the referred to module</li>
<li>Does <strong>not</strong> copy methods from a module into a class</li>
<li>So modules are actually shared</li>
</ul></li>
<li><p><code>extend</code></p>

<ul>
<li><code>include</code>s into this object&#8217;s class&#8217; singleton class.</li>
</ul></li>
</ul>

<h2>Metaprogramming</h2>

<ul>
<li><code>instance_eval</code>

<ul>
<li>Changes <code>self</code> to the receiver of <code>instance_eval</code></li>
<li>Me: Cheeky way to call private methods on objects</li>
</ul></li>
<li><p><code>class_eval</code></p>

<ul>
<li>Changes <code>self</code> to the receiver (a class) of <code>class_eval</code></li>
<li>WTF is the current class?  Still not clear on this &#8212; and DT was getting confused too!  <strong>Oy vey!</strong></li>
</ul></li>
<li><p>&#8220;Top level&#8221; methods are defined on a singleton instance of Object</p>

<ul>
<li><code>to_s</code> is redefined here as well to return &#8220;main&#8221;</li>
<li>Slide 167 explains the toplevel environment (although you&#8217;re not really in instance_eval)</li>
</ul></li>
<li><p>Me: I actually found the Object Model discussion far more intense than playing with define&#95;method &#8212; probably because I&#8217;m already pretty comfortable with meta/reflective programming from Java and having already used a fair bit of define&#95;method and eval.</p></li>
<li><p>DT: Use of <code>method_missing</code> involves two method calls so it&#8217;s a bit slower.</p></li>
<li><code>initialize_copy</code>

<ul>
<li>Define this to override the behavior of <code>dup</code> &#8212; to possibly provide a deep copy</li>
</ul></li>
<li><code>const_missing</code>

<ul>
<li>Rails uses this to require files at runtime</li>
<li><code>const_get</code>Can only call on one class at a time.</li>
</ul></li>
</ul>

<p><pre>
  class Foo
    class Bar
      class Blech
      end
    end
  end</p>

<p>c = self.class.const<em>get &#8220;Foo&#8221;
  c = c.const</em>get &#8220;Bar&#8221;
  c = c.const_get &#8220;Blech&#8221;</p>

<p>puts c
  # >> Foo::Bar::Blech
</pre></p>

<p>The below example was in the Rails class but makes even more sense today thanks to our discussions of <code>include</code> and <code>extend</code>:</p>

<h2>Hooks</h2>

<ul>
<li><code>included</code></li>
</ul>

<p><strong>Mixin a Module containing both instance methods and &#8220;class&#8221; methods</strong>
<pre>
module Foo
  def self.included(klass)
    klass.extend ClassMethods
  end</p>

<p>def foo
    puts &#8220;foo&#8221;
  end</p>

<p>module ClassMethods
    def class_foo
      puts &#8220;class foo&#8221;
    end
  end
end</p>

<p>class Person
  include Foo
end</p>

<p>Person.new.foo
Person.class_foo
</pre></p>

<ul>
<li><p><code>inherited</code></p></li>
<li><p>Explain why garbage collection in MRI &#8217;sucks&#8217; (Me: Certain individuals I know, who shall remain nameless, &#42;cough&#42;Toby DiPasquale&#42;cough&#42; have commented on this)</p>

<ul>
<li>DT</li>
<li>Typically not a problem</li>
<li>However, if you have a LOT of loose objects (100s of thousands&#8230; try creating a String by concat&#8217;ing lots of Strings together).

<ul>
<li>Had a program that did this.  Instead of concat&#8217;ing several times, accumulated the Strings in an Array and created it at the end</li>
<li><strong>Performance went from two minutes to one second</strong></li>
</ul></li>
<li>JRuby uses the JVM garbage collector (<strong>GOOD</strong>)</li>
<li>Rubinius is better</li>
<li>1.9 is better</li>
</ul></li>
</ul>

<h2>&#8230; make it fast</h2>

<ul>
<li>CF rant about maintainability.  No argument here.</li>
<li>benchmark.rb

<ul>
<li><code>Benchmark#bmbm</code> (great name) does a rehersal run first and then a real run</li>
</ul></li>
<li>For socket code

<ul>
<li>Socket::do&#95;not&#95;reverse&#95;lookup = true</li>
</ul></li>
<li>YAML

<ul>
<li><code>YAML#dump</code> == slow</li>
</ul></li>
<li><p>update&#95;page in Rails</p>

<ul>
<li>Calling in more than 15 times for a single page will cause a noticeable slowdown</li>
</ul></li>
<li><p>ObjectSpace</p>

<ul>
<li>Iterate through objects and ue <code>Marshal#dump</code> to determine amount of memory taken up by a certain class</li>
</ul></li>
<li><p>To speed things up  </p>

<ul>
<li>C (and other) extensions</li>
<li>DL (dynamic linking) &#8212; link a library at runtime and use it directly</li>
<li>Requires mapping C function calls (and structs if used) to Ruby objects

<ul>
<li>Slide 115-6</li>
</ul></li>
</ul></li>
<li><p>Some lecture on good ol&#8217; fashioned CS: O(n), O(n^2), and avoiding stupid loops</p>

<ul>
<li>Wow, DT cites Sedgewick (Me: I learned wth Corman)</li>
</ul></li>
<li>Now CF is talking about eager loading and caching as a way of optimizing runtime.</li>
<li>This afternoon just seems like&#8230; common sense programming/software engineering/computer science that every student in here ought to have.  </li>
<li>&#8220;Memoization&#8221;

<ul>
<li>Caching values of expensive operations for later re-use</li>
<li>There are some gems/libraries out there to keep code cleaner</li>
<li>Basically just the use of the <code>||=</code> idiom</li>
</ul></li>
</ul>

<p><strong>Exercise</strong> <a href="http://pastie.caboo.se/194517">Playing with memoization Fibonacci to run super-fast</a></p>

<h2>Library Organization</h2>

<ul>
<li>Discussion of setup.rb and RubyGems</li>
<li>Having written a few gems and installed who knows how many, this section of the class is mind-numbing

<ul>
<li>Dr. Nic&#8217;s NewGem gem essentially obviates much of this section of the class.  Just use NewGem, write your own little gem, play with it, and that will teach you plenty.</li>
</ul></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/09/advanced-ruby-studio-day-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Advanced Ruby Studio, Day One</title>
		<link>http://evan.tiggerpalace.com/2008/05/08/adv-ruby-studio-day-one/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/08/adv-ruby-studio-day-one/#comments</comments>
		<pubDate>Thu, 08 May 2008 17:01:36 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/08/adv-ruby-studio-day-one/</guid>
		<description><![CDATA[Notes after the jump (as I write them)

Review of the day: Morning session was excellent and intense.  This afternoon has been theory.  As of 3:45pm, it hasn&#8217;t felt so &#8220;advanced&#8221;.



Blocks, Procs, and Closures


&#8220;Brace&#8221; form of block always associates it self with the nearest method call.  Not true of do ... end
break


break takes [...]]]></description>
			<content:encoded><![CDATA[<p>Notes after the jump (as I write them)</p>

<p>Review of the day: Morning session was excellent and intense.  This afternoon has been theory.  As of 3:45pm, it hasn&#8217;t felt so &#8220;advanced&#8221;.</p>

<p><span id="more-51"></span></p>

<h2>Blocks, Procs, and Closures</h2>

<ul>
<li>&#8220;Brace&#8221; form of block <strong>always</strong> associates it self with the nearest method call.  Not true of <code>do ... end</code></li>
<li><code>break</code>

<ul>
<li><code>break</code> takes an optional parameter &#8212; which becomes the return value of the block.</li>
<li>So it&#8217;s behaving like a typical Proc return value except we&#8217;re jumping the call stack</li>
<li>Freaky that we&#8217;re all getting so bent out of shape on like the first slide or two of the real content. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </li>
</ul></li>
<li><code>next</code>

<ul>
<li>Just return from the block early</li>
<li>Similarly, has an optional parameter that is the return value of the Proc</li>
</ul></li>
<li><code>redo</code>

<ul>
<li>Me: I&#8217;ve never used it</li>
<li>DT: Used it maybe 3 times in 8 yars of Ruby</li>
</ul></li>
<li>Ooooh, I have softcopy of all of the code samples from the class (but almost certainly can&#8217;t redistribute, sorry)</li>
<li><code>retry</code>

<ul>
<li>Ok, didn&#8217;t know this one&#8230;</li>
<li>Like <code>redo</code> except that it <strong>reevaluates the CALL to the proc</strong> so the below example could be implemented with <code>retry</code></li>
</ul></li>
</ul>

<p><pre>
  i = 0
  loop_until i == 3 do
    i += 1
  end
</pre></p>

<p>&#8230; because <code>retry</code> will reevaluate the loop&#95;write call which <strong>reevaluates</strong> the <code>i &lt; 3</code> call.  <strong>And this is getting removed from Ruby 1.9</strong> (but will still be available for exception handling)</p>

<p>Hrmph.  Blocks aren&#8217;t Procs in MRI unless you pass a &amp; on the param to the method.<br />
DT: There are two kinds of Proc objects differentiated by a hidden flag</p>

<ul>
<li>Using <code>lambda</code>, behaves like an anonymous method</li>
<li>Using <code>Proc.new</code>, get an object that behaves like an inline block</li>
<li><code>proc</code> changed from an alias to <code>lambda</code> to <Proc.new</code></li>
<li><p>Me: Glad that I&#8217;ve always just used <code>lambda</code></p></li>
<li><p>Bindings</p>

<ul>
<li>Ruby stack frames point to Binding objects</li>
<li>Me: Used in the common Ruby implementations under the cover?</li>
<li>DT: They must      </li>
</ul></li>
<li>Closures

<ul>
<li>Whenever a block is creating, it automatically gets a Binding to the current stackframe</li>
<li>Me: So that&#8217;s how we get closures.  Cool.  Follows like 1 + 2 = 3</li>
<li>Blocks need the local Binding in order to be able to implement loop constructs</li>
<li>CF: Multiple calls to <code>binding</code> return different wrappers to the stack frame&#8217;s Binding &#8212; so they can&#8217;t be compared at runtime.</li>
<li>Methods are not closures</li>
</ul></li>
</ul>

<p>We were given a fun little exercise to write a counter method using a Proc.  Below is my Java-ish solution initializing a counter to nil.</p>

<pre>
def counter(start = 0, increment = 1)
  count = nil
  lambda {
    count += increment if count
    count ||= start
  }
end

c = counter(10, 2)
p c.call
p c.call
p c.call
</pre>

<p>My neighbor today, Jimmy Baker, tried something that I liked.  He passed a added a third parameter on the <code>counter</code> method and used that instead of defining a local variable in the method impl.  I thought this was cute because the arguments to the method are also part of the Binding and so could save another line of code. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>

<h2>Ruby Internals</h2>

<ul>
<li>Ruby C extensions are running in the same runtime

<ul>
<li>So ParseTree, for instance, can walk the parse tree</li>
<li>Me: I&#8217;ve read about ParseTree (and Ruby2Ruby).  Cool stuff.</li>
</ul></li>
<li>Now we&#8217;re poking a little through Ruby 1.8.6&#8217;s parse.y (written in yacc) looking at the definition of <code>stmt</code> and <code>compstmt</code>.  Uf da!</li>
<li>eval.c

<ul>
<li><code>eval_node</code> is how Ruby walks it&#8217;s internal parsed tree of instructions</li>
</ul></li>
</ul>

<h2>Design in a Dynamic Language</h2>

<ul>
<li>DT: ranting about OO programming really being about classes and not objects.</li>
<li>Experienced Ruby programmers prefer composition and rarely use inheritance

<ul>
<li>Me: At least I&#8217;m on the right track</li>
</ul></li>
<li>Long argument about whether inheritance hierarchies (and static typing) are all that necessary.</li>
<li>DT: Cites how infrequently Java developers run into ClassCastExceptions when extracting Objects from collections (zero or one times per year) and how this problem was &#8220;fixed&#8221; with Java 1.5.</li>
<li>CF: Interesting minimalist view of the advantage of composition over inheritance: you only implement the methods that you need and can avoid exposing those that you don&#8217;t.</li>
<li>DT: <code>Forwardable</code> in std lib

<ul>
<li>Declarative delegation, i.e., <code>def&#95;delegator :@member, :member&#95;method, :exposed&#95;method</code> is clearer than:</li>
</ul></li>
</ul>

<p><pre>
  def exposed<em>method
    @member.member</em>method
  end
</pre></p>

<ul>
<li>Logical delegation via method_missing (simple stuff)</li>
<li>Duck typing</li>
<li>DT gave an example of prototype-based programming in Ruby: defining Objects and having Objects inherit from other Objects by use of <code>clone</code></li>
<li>CF: Why never to use <code>kind&#95;of?</code>: because objects can have methods remove at runtime just as easily as they can be added; it&#8217;s more important to know if an object can <code>respond&#95;to?</code> a particular message.

<ul>
<li>Knew this already but I love this explanation.</li>
</ul></li>
<li>CF: Points out how the Martin Fowler <em>Refactoring</em> book really turned him on to OO with &#8220;Handle Conditions with Polymorphism&#8221;.  With Ruby, just reopen the class, add different impls to each possible object with the same method name, remove the conditional, and just invoke the method outright in the code.</li>
<li>Mixins

<ul>
<li>Look for &#8220;-able&#8221; descriptions (i.e., Loggable, Enumerable, Printable, etc.) and sometimes &#8220;-ing&#8221;</li>
<li>CF on splitting methods up: When I have comments in a method, that&#8217;s a big hint</li>
<li>Me: Yup.  And, wow, do I see a lot of code like that (No, I usually didn&#8217;t write it!)</li>
<li>Minimize interaction between Mixin and including class &#8212; otherwise coupling the including Class to the Mixin</li>
</ul></li>
</ul>

<h2>Messin&#8217; With Types</h2>

<ul>
<li>to_x conversion methods just make a &#8220;best guess&#8221;</li>
<li>Coercion

<ul>
<li>Not supposed to be lossy</li>
<li>DT: Representation of one type in another type</li>
</ul></li>
<li><code>Symbol.to_proc</code></li>
<li><code>coerce</code>

<ul>
<li>DT: You&#8217;ll probably never need it</li>
<li>DT: Good example of double-dispatch</li>
</ul></li>
</ul>

<h2>&#8220;Homework&#8221;</h2>

<ul>
<li>Use <code>coerce</code> to write 1 + &#8220;123&#8243; to return 124</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/08/adv-ruby-studio-day-one/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Advanced Rails Studio Day 3 (Live Blogging)</title>
		<link>http://evan.tiggerpalace.com/2008/05/07/advanced-rails-studio-day-3-live-blogging/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/07/advanced-rails-studio-day-3-live-blogging/#comments</comments>
		<pubDate>Wed, 07 May 2008 09:00:00 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/07/advanced-rails-studio-day-3-live-blogging/</guid>
		<description><![CDATA[The day starts with a list of potential topics.  The class body votes on the topics that they want to cover.  All of my votes went to &#8216;file uploads&#8217; for work reasons &#8212; and fortunately this pushed it over the top!  

And the results in order are:


AJAX
File Uploads
Perf &#38; Scalability
Deployment
AR with unsupported [...]]]></description>
			<content:encoded><![CDATA[<p>The day starts with a list of potential topics.  The class body votes on the topics that they want to cover.  All of my votes went to &#8216;file uploads&#8217; for work reasons &#8212; and fortunately this pushed it over the top! <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>

<p>And the results in order are:</p>

<ol>
<li>AJAX</li>
<li>File Uploads</li>
<li>Perf &amp; Scalability</li>
<li>Deployment</li>
<li>AR with unsupported DBs</li>
<li>Debugging</li>
</ol>

<p>Notes after the jump:</p>

<p><span id="more-50"></span></p>

<h2>AJAX &amp; RJS</h2>

<ul>
<li>Motherhood and apple pie describing RJS, Prototype, and Script.aculo.us at a high level</li>
<li>DT: Believes that fewer web developers (well, he said &#8220;Rails&#8221;) are trying to emlate desktop applications with AJAX

<ul>
<li>Me: Or those few that are do a better job?  (i.e., <a href="http://meebo.com">Meebo</a>)</li>
</ul></li>
</ul>

<pre>
ruby -e "self.javascript_guru?"
=> false
</pre>

<ul>
<li>Hopefully this doesn&#8217;t surprise anyone (again, motherhood and apple pie here) but: RJS generates JavaScript server side and sends the JS back to Prototype which evals the generated JavaScript which updates the DOM.</li>
<li>For custom JS:

<ul>
<li><code>page &lt;&lt; "raw javascript here"</code> and it concatenates the JS in order with the other calls to page.</li>
</ul></li>
<li>Interesting to me: the &#8220;Old Way&#8221; involves generating DOM IDs in the calling view and the RJS &#8212; been there done that

<ul>
<li>In Rails 2.0: the <a href="http://agilewebdevelopment.com/plugins/simply\_helpful"><em>&#8220;simply&#95;helpful&#8221; plugin</a> provides a <code>div&#95;for</code> and <code>tag&#95;for</code> that generate the IDs for you</em>.  Sweet!</li>
<li>From the audience: JRails is a plugin that monkey-patches Rails to support JQuery.  From toying with JQuery a little, I &lt;3 it.</li>
</ul></li>
<li><code>page.select</code> takes a CSS selector and generates appropriate GS</li>
</ul>

<pre>
  page.select("div.queston").each do |q|
    q.visual_effect ....
  end
</pre>

<ul>
<li>I dig it.  </li>
<li>DT: Refactor into a helper if you&#8217;re going to reuse this (yup yup)

<ul>
<li>page[:an_element].reload seeks out a partial &#8220;&#95;an&#95;element.erb&#8221; and updates the element</li>
<li><code>update&#95;page { |p| p.alert("Hello!") }</code> just generates a String</li>
<li>Can be called from controller, helper, or view</li>
<li>CF: <em>puts his RJS in the controller</em>!  His RJS code tends to be very short.  If you&#8217;re doing more than that, then you&#8217;re probably making a busy page.  (This is a handy take away)</li>
</ul></li>
</ul>

<p>Example:
<pre>
  render :update do |page|
    page[:foo].your&#95;rjs&#95;operation
  end
</pre></p>

<ul>
<li>To &#8216;easily&#8217; support AJAX and synchronous:</li>
</ul>

<pre>
  respond_to do |format|
    format.html { do something }  # handles text/html http requests
    format.js                     # causes lookup of RJS if making an AJAX request
  end
</pre>

<ul>
<li>CF: Can call <code>update&#95;page</code> as often as you want unlike <code>render</code>

<ul>
<li>Makes it easy to mix JS, HTML, and Ruby in the view &#8212; but could get ugly</li>
<li>So write helpers to be called via <code>link&#95;to&#95;function</code> (Slide 205 and 206)</li>
</ul></li>
<li><p>Audience remark: Testing a page that can respond to text/html and a JS request seems as though it can be brittle/hard to test</p>

<ul>
<li>CF: Yes, it&#8217;s harder to test a site that does AJAX than one that does not</li>
<li>DT: <strong><em>Triple good point!: With AJAX, you have to consider how friendly your website is to screen readers.</em></strong>  I hope that my current colleagues are reading this&#8230;.</li>
</ul></li>
<li><p>Writing your own RJS extensions:</p>

<ul>
<li>The JS generators uses <code>method&#95;missing</code> so <code>page.lightbox.dosomething</code> would invoke <code>Lightbox.dosomething</code> in JS.</li>
<li>Be careful of the page size resulting from all of the code generated into the HTML</li>
</ul></li>
</ul>

<p><strong>break</strong></p>

<h2>File Uploads</h2>

<ul>
<li><p>Two basic solutions:</p>

<ul>
<li>attachment&#95;fu plugin</li>
<li>paperclip</li>
<li>Biggest recipe in the Advanced Recipes book and freely available on the book site</li>
</ul></li>
<li><p>Topics interesting to audience</p>

<ul>
<li>Performance (my question)</li>
<li>Custom Mongrel handler

<ul>
<li>CF: Should be about 10 lines of code</li>
<li>MC: Code should be out there somewhere</li>
</ul></li>
<li>Merb (obvious solution but thicker than it used to be?) &#8212; started as a custom Mongrel handler</li>
<li>Multiple concurrent uploads (also of interest) </li>
<li>Me: See <a href="http://brainspl.at/articles/2007/04/23/slides-from-my-mongrel-merb-talk">Ezra&#8217;s talk on this</a></li>
<li>Progress bars</li>
</ul></li>
<li><p>attachment&#95;fu (yes, I&#8217;ve never used it.  Shoot me.)</p>

<ul>
<li>In events&#95;final web app:</li>
<li>User has a Portrait</li>
<li>Portrait <code>has&#95;attachment</code> is monkey-patched into AR (See code sample in events&#95;final)</li>
<li>Some columns in the DB are required by attachment&#95;fu

<ul>
<li>parent&#95;id</li>
<li>width</li>
<li>height</li>
<li>content&#95;type</li>
<li>filename</li>
<li>thumbnail (can have several)</li>
</ul></li>
<li><strong>Interesting notion of creating a logical model (in that it is not represented by a table in the DB)</strong> &#8220;PortraitService&#8221; (crappy name) delegate to:</li>
<li>create a transaction to handle the tasks of:

<ul>
<li>destroying an existing portrait</li>
<li>assigning the portrait to a user</li>
<li>saving the portrait</li>
</ul></li>
<li>handle updates to the portrait</li>
</ul></li>
<li><p>Little disappointed that the PragProg guys weren&#8217;t prepared to discuss custom Mongrel handlers due to Rails single-threaded limitation.  Mentioned it to Chad as a future add for the course.  <a href="http://merbivore.com">Merb</a> wouldn&#8217;t even exist if this wasn&#8217;t a severe limitation with Rails; Ezra started it as just a simple custom Mongrel handler.</p></li>
<li><p>And, given my input, Chad is digging it into a little now. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>

<ul>
<li>mongrel_cluster.yml</li>
<li>config_script option allows specification of custom Mongrel handler</li>
</ul></li>
</ul>

<p><pre>
require 'mongrel'
class MyHandler &lt; Mongrel::HttpHandler
  def process(req, res)
    res.start do |out|
      out.write something     # do something useful here
    end
  end
end</p>

<p>uri &#8220;/myuploadhandler&#8221;, MyHandler, :in_front => true
</pre></p>

<ul>
<li>And just post to the URI specified in the custom handler.</li>
<li>This <strong>will</strong> run in a separate thread (which is the point)</li>
</ul>

<h2>Performance and Scaling</h2>

<p>Really only have conceptual knowledge of this myself so the nitty gritty examples here were really handy.</p>

<ul>
<li>Key points

<ul>
<li><strong>Measure performance often</strong></li>
<li><strong>Identify hotspots</strong></li>
<li><strong>Change one thing at a time</strong></li>
<li><strong>Iterate</strong></li>
</ul></li>
<li>This jibes with Ezra&#8217;s remarks about performance optimization when he first started talking about custom Mongrel handlers and led into Merb.</li>
<li>Corollary: <strong>Guessing at performance bottlenecks is a waste of time.</strong></li>
<li>MC quoting Ezra: <strong>&#8220;Post-mature optimizations are the cost of most hosting bills&#8221;</strong></li>
<li>Optimizing AR

<ul>
<li>Look at the log files</li>
<li>Obviously, AR-generated queries could be ugly &#8212; so look at log files early</li>
<li>DT: Requests/second is the most useless statistic in the log file</li>
<li>DT: <strong>AR makes life simple &#8212; and sometimes simple is stupid</strong></li>
<li>Selective Columns</li>
<li>Custom finders:

<ul>
<li>Use the :select option to specify the columns to pull.</li>
<li><strong>Pull the ID column</strong> to avoid possible silent DB failure (DB specific)</li>
</ul></li>
<li>Preloading Child Rows</li>
<li>For N + 1 queries (i.e. <code>has&#95;many :line&#95;items</code> that may have products itself)

<ul>
<li>Use of <code>:include => :product</code></li>
<li>MC mentioned yesterday, take care with use of :include</li>
<li>DT: Please, please, measure when using :include.  It may not help performance.</li>
<li>MC: suggests having separate associations for explicitness (readability and performance)</li>
</ul></li>
</ul></li>
</ul>

<p><pre>
  has&#95;many line&#95;items
  has&#95;many line&#95;items&#95;with&#95;products :include => product
</pre></p>

<ul>
<li>Assigning query results to a constant in an AR class that will load the results at startup and cache the results in the object model

<ul>
<li>Great for things that don&#8217;t change such as countries, states, etc.  </li>
</ul></li>
<li>ActiveRecord Query Cache

<ul>
<li>Based in identical SQL</li>
<li>Cleared on CUD</li>
</ul></li>
</ul>

<p><pre>
  Event.cache do |e|
    e.find(1) # DB
    e.find(1) # Cache
    e.update
    e.find(1) # DB
  end
</pre></p>

<ul>
<li>Cache Store (Rails 2.1 &#8212; so still Edge)

<ul>
<li>API for configuring default store

<ul>
<li>Supports memory, file system, DRb (WTF?), <strong>memcache</strong></li>
<li>So I ask: For memcache, this means a shared cache for a Mongrel cluster?</li>
<li>MC: yes</li>
<li><strong>Sweet!</strong> (Yes, I loved <a href="http://www.imdb.com/title/tt0242423/">Dude, Where&#8217;s My Car</a>)</li>
</ul></li>
</ul></li>
</ul>

<p><pre>
  store = ActionController::Base.cache_store
  store.write(key, value)</p>

<p>stuff = store.fetch(key) do
    ARClass.stuff(key)
  end
</pre></p>

<ul>
<li>Note that this is not just for ActiveRecord</li>
<li>Allows for caching <strong>across requests</strong></li>
<li>Even more complex examples on slide 309</li>
</ul>

<p><strong>lunch</strong></p>

<ul>
<li>Page Caching

<ul>
<li>Pages that don&#8217;t take any parameters</li>
<li>Pages that don&#8217;t change</li>
<li>Cron job for cleaning up cache</li>
<li>Can&#8217;t cache

<ul>
<li>Personalized pages, pages w/ params, pages w/ content changes, time-based content

<ul>
<li>Although, for the latter, you could cache and force a refresh by destroying the cache periodically&#8230;</li>
</ul></li>
</ul></li>
</ul></li>
</ul>

<pre>
class SomethingsController < ApplicationController
  caches_page :index, :show
end
</pre>

<ul>
<li>Fragment Caching

<ul>
<li>Cache small parts of templates</li>
<li><code>cache</code> can be further parameterized to cache per user, etc.</li>
<li>Expiring specification is available in 2.1 

<ul>
<li>But also via plugin: (see Karen Gillison)</li>
</ul></li>
</ul></li>
</ul>

<p><pre>
  <% cache('some label') do -%>
    Your HTML goes here
  <% end -%>
</pre></p>

<ul>
<li><p>Expiring caches</p>

<ul>
<li>expire_page</li>
<li>expire_action</li>
<li>expire_fragment</li>
</ul></li>
<li><p>Sweepers</p>

<ul>
<li>For cleaning up caches</li>
<li>Observes models</li>
<li>Lifecycle actions on Sweeper get invoked when the lifecycle actions on the observed Model get invoked</li>
<li>Slide 319</li>
<li>In the controller, have to specify the Sweeper (see below)</li>
<li>To avoid having observers impact performance of transactions, put the expirey on a queue and operate on it later.

<ul>
<li>Me: If this were J2EE, shove it into a JMS queue &#8212; but J2EE&#8230;. ick.</li>
</ul></li>
</ul></li>
</ul>

<p><strong>DT: Complaining about the number of moving parts that are now being integrated into Rails: memcached, Starling, multiple Mongrels, Ferret, etc.  Deployment is more painful than J2EE (Sadly, agree violently).  Waiting for a backlash to occur at the complexity of it.  Look at Twitter and how often it fails due to some SPOF (single point of failure).  People writing many of the tools/plugins do not have enterprise experience and so are not taking external dependencies into account.</strong></p>

<p><pre>
class MyController....
  cache<em>sweeper :my</em>sweeper
end
</pre></p>

<ul>
<li><p>Memcache</p>

<ul>
<li>Basically an in-memory hash (that you do not always need to use depending on your app)</li>
<li>cache_fu at the model level 

<ul>
<li>supports TTL</li>
<li>Probably less relevant as of Rails 2.1</li>
</ul></li>
</ul></li>
<li><p>HTTP Performance</p>

<ul>
<li><code>javascript&#95;include&#95;tag(:all, :cache => true)</code>

<ul>
<li>Combines (and possibly compresses) JS files</li>
</ul></li>
<li><code>ActionController:Base.asset&#95;host = 'asssets%d.example.com'</code> 

<ul>
<li>Allows for federating assets across servers to avoid browser-limited number of connections per server</li>
</ul></li>
<li><a href="http://developer.yahoo.com/yslow/">Yslow Firebug plugin</a> (Andrew Willis mentioned this to me at lunch on Monday)</li>
<li>Tools

<ul>
<li>httperf</li>
<li>Siege</li>
<li>Profiler</li>
</ul></li>
</ul></li>
<li><p>General Points</p>

<ul>
<li><strong>Don&#8217;t use file-based sessions</strong></li>
<li>Don&#8217;t forget indices</li>
<li>Watch the log</li>
<li>Cache where useful</li>
</ul></li>
<li><p>DT: Consider adding some automated monitoring tools to determine when the system is beginning to perform badly</p></li>
</ul>

<p><strong>break</strong></p>

<ul>
<li>Worth noting that AOL Photos uses Rails &#8212; if you&#8217;re looking for another example of a large company relying on Rails.</li>
</ul>

<h2>Deploying</h2>

<ul>
<li>Deploy early

<ul>
<li>Me: It was personal development, but I was impatient to deploy the first (and only so far) time that I&#8217;ve used Capistrano.  Better if I had tried to deploy earlier to forego that.  Similar to TDD/BDD: makes the behavior less painful.</li>
</ul></li>
<li>How many Mongrels in a cluster?

<ul>
<li>MC: Varies but fewer than you think</li>
</ul></li>
<li>Question about not needing Mongrels

<ul>
<li>CF/DT: mod&#95;rails &#8212; still in beta</li>
<li>Ruby processes that Apache comunicates with via *NIX sockets</li>
<li>Forking a process &#8212; so as some point out its similar to FastCGI</li>
<li>MC: There&#8217;s also Thin, Ezra&#8217;s work tying Rack and Rails together  </li>
</ul></li>
<li>MC: They started by using Apache 2.2.x

<ul>
<li>mod_rewrite</li>
<li>mod&#95;proxy&#95;balancer</li>
</ul></li>
<li>Nginx

<ul>
<li>Small memory footprint</li>
<li>Easier to configure than Apache</li>
<li>MC: unless you have a damn good reason, pick Nginx (I need to use this beast &#8212; been hearing about it for over a year&#8230;)</li>
</ul></li>
<li>&#8220;Heartbeat&#8221;

<ul>
<li>Custom Mongrel handler excellent for this</li>
</ul></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/07/advanced-rails-studio-day-3-live-blogging/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Advanced Rails Studio Day 2 (Live-blogging)</title>
		<link>http://evan.tiggerpalace.com/2008/05/06/advanced-rails-studio-day-2/</link>
		<comments>http://evan.tiggerpalace.com/2008/05/06/advanced-rails-studio-day-2/#comments</comments>
		<pubDate>Tue, 06 May 2008 21:59:50 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Ruby]]></category>

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

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

		<guid isPermaLink="false">http://evan.tiggerpalace.com/2008/05/06/advanced-rails-studio-day-2/</guid>
		<description><![CDATA[Notes follow after the jump.



Metaprogramming Rails


How to write &#8220;magic&#8221; (ha!) such as belongs_to
&#8220;Is there a way to track down the file where a modification was made to a class?&#8221;


DT: Cause it to raise an error.  Otherwise, no.
OUCH

DT whips up a little example showing how Rails implements Numeric.kilobytes



class Numeric
  def kilobytes
    [...]]]></description>
			<content:encoded><![CDATA[<p>Notes follow after the jump.</p>

<p><span id="more-49"></span></p>

<h2>Metaprogramming Rails</h2>

<ul>
<li>How to write &#8220;magic&#8221; (ha!) such as <em>belongs_to</em></li>
<li>&#8220;Is there a way to track down the file where a modification was made to a class?&#8221;

<ul>
<li>DT: Cause it to raise an error.  Otherwise, no.</li>
<li><em>OUCH</em></li>
</ul></li>
<li>DT whips up a little example showing how Rails implements Numeric.kilobytes</li>
</ul>

<pre>
class Numeric
  def kilobytes
    self * 1024
  end
end
</pre>

<ul>
<li>Of course, ActiveSupport just includes a definition that does something similar.</li>
<li>Question: does it speed up start up time to cherry pick what you want to load?

<ul>
<li>DT: It&#8217;s pretty trivial to load active_support in the grand scheme of loading Rails</li>
</ul></li>
<li>DT describing how a class definition is executable code (recap of NoVaRUG presentation from April)

<ul>
<li>Just reopening ActiveRecord::Base and adding class methods.  Waiting for the Adv Ruby class. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </li>
<li>More simple metaprogramming examples.  Goofing off while waiting for the harder core stuff.</li>
</ul></li>
<li>They should&#8217;ve called this section &#8216;Ruby eye for the PHP guy&#8217;.  Boooooring&#8230;&#8230;

<ul>
<li>But, in the meantime, I have Markdown working in WordPress now.  Yay.</li>
</ul></li>
<li>Ok, ok, the &#8220;lib&#8221; directory in Rails is in the LOAD_PATH.  Not a huge surprise but there ya go.</li>
<li>Adding methods dynamically at the class level

<ul>
<li>DT is describing the use of <code>Object#extend</code>.  Honestly, I haven&#8217;t used that in anger before; I&#8217;ve always been a <code>class &lt;&lt; self; do_stuff; send</code> guy.  But, yeah, definitely simpler if you just want to add methods to the singleton object on a Class.</li>
</ul></li>
<li>Decent question: What if you have a module with both class and instance methods?

<ul>
<li>Don&#8217;t use <code>Object#extend</code> (makes sense)</li>
<li>Have to use <code>Module#include</code></li>
<li>In the implementing Module, Rails will look for a method called <code>included</code> that contains the methods that should be put in the class.</li>
</ul></li>
</ul>

<p><pre>
Module Foo
  def self.include(base)
    base.extend(ClassMethods)
  end</p>

<p>module ClassMethods
    def method<em>that</em>will<em>be</em>a<em>class</em>method_shortly
    end
  end
end
</pre></p>

<ul>
<li>Where the hell is <code>Module#included</code> called from?

<ul>
<li><strong>Awesome</strong> question: Why is <code>foo.&#95;&#95;send__ :include, module</code> used in some places instead of <code>include module</code>?</li>
</ul></li>
<li><em>Because the former doesn&#8217;t cause a class to load if it isn&#8217;t already loaded.</em>  Fucking cool!  If only it was a little more obvious&#8230;</li>
</ul>

<p><strong>Break</strong></p>

<ul>
<li>DT: &#8220;<code>Kernel#eval</code> is the work of the devil.&#8221;</li>
<li>Didn&#8217;t realize: <code>Kernel#eval</code> accepts an optional Binding (<code>Kernel#binding</code>)&#8230;</li>
<li>DT is giving some examples of Bindings.  Surprised that this came up in a Rails class.

<ul>
<li>And just as I was starting to ask &#8220;What&#8217;s the difference between Bindings and Continuations?&#8221; (other than having a stack&#8230;), DT mentions that a &#8220;Continuation is a Binding on steroids&#8221; and will be discussed in the Adv Ruby Studio later this week.  Bring on the pain!</li>
</ul></li>
<li>And now <code>Object#instance_eval</code></li>
<li>DT is giving a nice simple example of closures:</li>
</ul>

<pre>
def twice
  yield
  yield
end

name = "Evan"
twice do
  puts "Hello #{name}"
end
</pre>

<ul>
<li>name is defined outside the block before twice is invoked.  The yield call is evaluating name based on it&#8217;s definition at the time of the <code>twice</code> call.</li>
</ul>

<p>Another example:
<pre>
def hello(name)
  lambda {
    puts "hello #{name}"
  }
end</p>

<p>c = hello &#8220;Evan&#8221;
c.call
</pre></p>

<p><code>name</code> is out of scope at the time of the call but <code>name</code> is stil referenced by the block&#8217;s Binding.</p>

<p>And&#8230;.</p>

<pre>
  def hello(name)
    count = 0
    lambda {
      puts "Hello, #{name} with count #{count}"
      count += 1
    }
  end

  c = hello "Evan"

  c.call
  c.call
  c.call
  c.call
  c.call
</pre>

<p>&#8230;returns:</p>

<pre>
  Hello, Evan with count 0
  Hello, Evan with count 1
  Hello, Evan with count 2
  Hello, Evan with count 3
  Hello, Evan with count 4
</pre>

<p>&#8230; because count is referenced by the block&#8217;s Binding</p>

<p>DT mentions later: <em>blocks are evaluated only when they are called</em></p>

<ul>
<li><code>Module#define_method</code></li>
</ul>

<p>Take 1:<br />
<pre>
  def definer
    def hello
      puts "I've defined a method inside of the execution of another method"
    end
  end</p>

<p>definer
  hello
</pre></p>

<p>Or the better way of doing it&#8230;
<pre>
  class Definer
    def self.define
      define_method(:hello) do
        puts "I've defined a method inside of the execution of another method"
      end
    end
  end</p>

<p>Definer.define
  Definer.new.hello
</pre></p>

<p>The above example invokes <code>Module#define_method</code> inside of a class because it&#8217;s a Module method; you can&#8217;t access it unless you&#8217;re inside of a Module (or Class because Class extends Module).</p>

<p>And here we use a closure within the example:</p>

<pre>
  class Definer
    def self.define(name)
      define_method(name) do |p|
        puts "I've defined a method called #{name} that was passed an arg #{p}"
      end
    end
  end

  Definer.define("hello")
  d = Definer.new
  d.hello "Evan"
  d.hello "Spock"
</pre>

<p>Nifty.  The string that we&#8217;re writing gets evaluated when <code>hello</code> is called.</p>

<p>DT says &#8220;I use define_method all over the place&#8221;.  Ok, ok, no more <code>Object#eval</code> for me.  &#8220;This is a closer to God way of doing Ruby duplication&#8221;.  Nice.</p>

<p>Note to self: Slide 129 in the slide package has the <code>Module#define_method</code> example.</p>

<p>DT: <em>Ruby is slower than most scripting languages because (1) it&#8217;s not written for speed and (2) it&#8217;s completely OO and classes are open.</em>
DT: The overhead of define<em>method versus def is &#8220;microscopic&#8221;.
Question: When would you use define</em>method?  It&#8217;s a little different than code generation.
  * Will be discussed more in the Adv Ruby Studio (GOOD!)</p>

<p><strong>Lunch</strong></p>

<h2>ActiveRecord</h2>

<ul>
<li>Joining Models

<ul>
<li>Discussing notion of creating relational objects to handle a many-to-many</li>
<li>has_many :through on both sides (simple-ish stuff so far)</li>
<li>Simple example of Magazine with Readers joined via Subscriptions.</li>
<li>Note to self: Slide 137</li>
<li>Question: &#8220;Is there anything forcing you to &#8220;has many :through&#8221; on both sides of a relationship?</li>
<li>Honest question but nope.  Although the DB may expose a bi-directional relationship, the code doesn&#8217;t have to represent it.</li>
<li>Worth noting: adding a Magazine to the Reader will automatically create a Subscription because of the has_many :through</li>
<li>Most people in the room aren&#8217;t using HABTM often</li>
<li>Join Model or HABTM?</li>
<li>Users and Groups</li>
<li>Attendees and Events</li>
<li>None of the above sell me on HABTM</li>
<li>Products and Tags

<ul>
<li>Tagging?  </li>
</ul></li>
<li>Products and Related Products 

<ul>
<li>HABTM?  Maybe&#8230;.</li>
</ul></li>
<li>HABTM if there isn&#8217;t a good name?  I don&#8217;t know&#8230; I shun HABTM.  Besides, there&#8217;s almost always qualitative and/or quantitive information that&#8217;s associated with the relationship.  That warrants a join model.</li>
<li>CF mentions using :include => [:registrations => :event] to eager load all of the events assocaited with each registration</li>
<li>MC believes that the use of :include generally causes more problems than it solves</li>
<li>Self-referential HABTM</li>
<li>Example with Person and having friends</li>
<li>FUGLY (<strong>sixs</strong> hash entries to supply to HABTM to add and remove bidirectional relationships automatically &#8212; see slide 141)</li>
<li>I suggested a Join Model approach with Friendship</li>
<li>DT: enforced bi-directional relationships should be maintained by triggers.

<ul>
<li>In the context where the data may persist indefinitely (i.e., enterprise), enforcing the data constraints <strong>exclusively</strong> within the application is nonsense.</li>
<li>No one in the class pointed this one out.  I know that I, for one, lose sight of this.</li>
</ul></li>
<li>DT, MC, and CF: <strong>Don&#8217;t put raw finds in your controller</strong>.  Tightly couples controller to model implementation.  <strong>BAD</strong>.<br />

<ul>
<li>Good sense if you want to possibly swap out ORM implementations &#8212; which is quite possile if you&#8217;re using ActiveRecord.</li>
</ul></li>
<li>CF: Shows the Friendship example which is better but still doesn&#8217;t let the DB be responsible for the relationship.

<ul>
<li>MC example:</li>
</ul></li>
</ul></li>
</ul>

<p><pre>
class Person
  has_many :friendships, :dependent => :destroy
</pre> </p>

<p>will call <code>destroy</code> on the the Friendship when the Person object is destroyed.</p>

<pre><code>  * Again, triggers would handle it better....
</code></pre>

<p>* Polymorphic Associations</p>

<p><pre>
class Person &lt; ActiveRecord::Base
  has_many :addresses, :as => :addressable
end</p>

<p>class Company &lt; ActiveRecord::Base
  has_many :addresses, :as => :addressable
en</p>

<p>class Address &lt; ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end
</pre></p>

<ul>
<li>The addresses table then needs &#8220;addressable<em>id&#8221; and &#8220;addressable</em>type&#8221; columns to indicate which row in which table (persons or companies) is related.</li>
<li>I&#8217;ve used these before and, really, polymorphic associations, in Rails, <strong>hurt</strong>!<br />

<ul>
<li><strong>I <strong>hate</strong> them</strong>.</li>
</ul></li>
<li>Someone else mentions single table inheritance as an option.  I&#8217;m not keen on that either but it is <strong>far</strong> less ugly than PA.</li>
<li><p>CF: If you use PA, <strong>you have to index the type field because you&#8217;re going to be querying it often</strong>.</p>

<ul>
<li>Single-Table Inheritance</li>
</ul></li>
<li>When you want to have an AR object inherit from another</li>
<li>Type field in the DB which contains the constant name of the type</li>
<li>Has all shared <em>and</em> distinct fields must be in the table</li>
<li>MC: Your STI table can get <em>very</em> wide if the classes in the family have little commonality&#8230;</li>
<li>CF: if you change the class name, you have to update the DB</li>
<li>CF: Ideally, prefer composition over inheritance

<ul>
<li>STI makes a strong case for composition &#8212; because STI can get very ugly&#8230;</li>
</ul></li>
<li>CF: Don&#8217;t use a column called &#8220;type&#8221; in AR &#8212; <strong>ever</strong>; bizarre-ass error messages.</li>
</ul>

<p><strong>break</strong></p>

<h2>Refactorings</h2>

<ul>
<li>Starting with an example controller action with a couple of raw finds</li>
<li>Interesting use of a code block on the <strong>AssociationProxy</strong>.

<ul>
<li>Below example seems reasonable if this query (i.e., recent) is only valuable on this relationship</li>
</ul></li>
</ul>

<pre>
  has_many :visits do
    def recent(limit = 5)
      find(:all, ...)
    end
  end
</pre>

<ul>
<li>Someone just pointed out that this doesn&#8217;t return an AssociationProxy (see <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html">here</a> and find &#8220;proxy&#8221;)

<ul>
<li>For example, it&#8217;s easy to believe that event.registrations is an Array (if both represent AR::Base objects)</li>
<li>It even says it&#8217;s an Array when you call <code>event.registrations.class</code></li>
<li>Calling <code>event.registrations.ancestors</code> reveals more</li>
<li>It&#8217;s actually an <strong>AssociationProxy</strong></li>
<li>See AR association_proxy.rb

<ul>
<li>Delegates everything to method_missing and from there to a wrapped target</li>
</ul></li>
<li>To extend an AssociationProxy with a module (in the example, called RecentFinder):</li>
</ul></li>
</ul>

<p><pre>
class User &lt; ActiveRecord::Base
  has_many :vists, :extend => RecentFinder
end
</pre></p>

<p>&#8230; which makes the former code sample, where we define a method to the AssociationProxy, much cleaner.</p>

<h2>Active Record Scoping</h2>

<ul>
<li><code>ActiveRecord::Base#with_scope</code> creates a block where all contained finder calls on the class use the specified scope

<ul>
<li>Slides 154 and 155 &#8212; <strong>want to review this more later</strong></li>
</ul></li>
<li>Named Associations</li>
</ul>

<pre>
  has_many :registrations
  
  has_many :preregistrations,
           :class_name => "Registration"
           :conditions => "pre_register is true"
</pre>

<ul>
<li><strong>These are cached</strong> (slightly evil that this is implicit &#8212; but a handy feature)</li>
<li>So a cool use is to nest scopes to and conditions together (but this isn&#8217;t cached &#8212; could suck performance wise for complex access control)

<ul>
<li>How many queries would we be performing?  One per scope?</li>
<li>__Nested calls to with<em>scope accumulate a single SQL query</em>_ so could be super awesome for complex access control (depending upon the SQL)

<ul>
<li>To be useful, this would have to be FAST!</li>
</ul></li>
</ul></li>
<li>Slides 159-160 lend themselves awesomely to access control (except need to know how to mark the cache dirty to force a refresh)</li>
</ul>

<p><strong>break</strong>  </p>

<h2>Custom Form Builders</h2>

<ul>
<li>Delegating the markup generation cleans up form code</li>
<li><code>FormHelper#form_for</code> takes a :builder argument.</li>
<li>Subclass of ActionView::Helpers::FormBuilder</li>
<li>When we call <code>form<em>for :builder => MyBuilder</code>, form</em>for yields with an instance of our builder as the argument.</li>
<li>Slide 177 contains the sample code for a simple LabelFormBuilder that dynamically generates methods that overrides much of the behavior o the DefaultFormBuilder but with our custom implementation.

<ul>
<li>That&#8217;s it.  Unless I need a form with a lot of unique formatting (which I can&#8217;t see happening often), I&#8217;m writing a customer FormBuilder.</li>
</ul></li>
<li>MC/CF: I asked how often these guys write custom FormBuilders.

<ul>
<li>Both use a custom FormBuilder in <strong>every</strong> project; they just may get someone who generates better UIs than they do to write it.</li>
<li><em>Unless I need a form with bizarre/unusual formatting, I&#8217;m going to be using one of these in the future.</em></li>
</ul></li>
<li>They also suggest writing a helper to wrap form_for to factor out the :builder option.</li>
<li><p><code>ActionView:Base.default<em>form</em>builder=</code>: Go assign your own default. <img src='http://evan.tiggerpalace.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p></li>
<li><p>content_for</p>

<ul>
<li>Page-specific content</li>
<li>JS</li>
<li>CSS includes</li>
<li>Contributing content (HTML) to the layout <strong>or any other template</strong>.</li>
<li>Smacks a little of goto&#8230;. so mighty but take care!</li>
</ul></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://evan.tiggerpalace.com/2008/05/06/advanced-rails-studio-day-2/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 3.455 seconds -->
