<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>August Lilleaas</title>
    <link>http://august.lilleaas.net/</link>
    <description>Articles and blog posts.</description>
    <language>en-us</language>
    <pubDate>Tue, 10 Nov 2009 22:50:01 GMT</pubDate>
    <lastBuildDate>Wed, 02 Sep 2009 19:48:12 GMT</lastBuildDate>
    <docs>http://cyber.law.harvard.edu/rss/rss.html</docs>
    <managingEditor>augustlilleaas@gmail.com</managingEditor>
    <webMaster>augustlilleaas@gmail.com</webMaster>
    <ttl>5</ttl>
 
    
    
    
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/augustlilleaas" type="application/rss+xml" /><feedburner:browserFriendly></feedburner:browserFriendly><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
      <title>Homebrew Is Awesome</title>
      <link>http://august.lilleaas.net/homebrew_is_awesome</link>
      <description>&lt;p&gt;&lt;a href="http://github.com/mxcl/homebrew"&gt;Homebrew&lt;/a&gt; by &lt;a href="http://www.methylblue.com/"&gt;Max Howell&lt;/a&gt; is an awesome OS X package manager. It makes Macports and Fink feel like a thing of the past, vastly outranking both of them in awesomeness.&lt;/p&gt;
&lt;h2&gt;Why is Homebrew awesome?&lt;/h2&gt;
&lt;p&gt;If Homebrew is Ruby, Macports and Fink is &lt;span class="caps"&gt;PHP&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Instead of only relying on it&amp;#8217;s own dependencies, it uses the software that comes with OS X. When you install Git, Homebrew uses the existing perl install rather than downloading and installing it&amp;#8217;s own. Awesome! I created a formula for &lt;a href="http://fishshell.org"&gt;fish&lt;/a&gt; in about 2 minutes. It installed without dependencies, because just like Git, OS X has all the dependencies fish requires.&lt;/p&gt;
&lt;p&gt;No sudo! You &lt;em&gt;can&lt;/em&gt; sudo if you want to, but why should you? More on that later.&lt;/p&gt;
&lt;p&gt;It leverages existing package managers, such as cpan, easy_install and rubygems. Why do the job that these package managers already does brilliantly?&lt;/p&gt;
&lt;p&gt;It&amp;#8217;s social. Since the formulas are &lt;a href="http://github.com/mxcl/homebrew"&gt;on github&lt;/a&gt;, you get the social aspects of github baked right into Homebrew. Wrote a formula? Fork the repo, add a pull request!&lt;/p&gt;
&lt;p&gt;And last but not least, formulas (or packages) are in Ruby. Double-awesome!&lt;/p&gt;
&lt;h2&gt;Installing with git&lt;/h2&gt;
&lt;ol&gt;
	&lt;li&gt;Run &lt;tt&gt;sudo chown -R `whoami`:staff /usr/local&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;cd /usr/local&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git init&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git remote add origin git://github.com/mxcl/homebrew.git&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git pull origin masterbrew&lt;/tt&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Installing without git&lt;/h2&gt;
&lt;p&gt;This process is a bit tedious.&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Run &lt;tt&gt;sudo chown -R `whoami`:staff /usr/local&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;Run &lt;tt&gt;curl -L -o homebrew.tar.gz http://github.com/mxcl/homebrew/tarball/masterbrew&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;If nothing happens here, run a few times until it works. Github randomly drops these requests for some reason.&lt;/li&gt;
	&lt;li&gt;Run &lt;tt&gt;tar xzf homebrew.tar.gz&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;Run &lt;tt&gt;cp -f mxcl-homebrew-[long sha here]/* /usr/local/&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;Run &lt;tt&gt;rm -rf mxcl-homebrew-[long sha here]&lt;/tt&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Usage&lt;/h2&gt;
&lt;dl&gt;
	&lt;dt&gt;Install&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;brew install git&lt;/tt&gt;&lt;/dd&gt;
	&lt;dt&gt;Remove&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;brew rm git&lt;/tt&gt;&lt;/dd&gt;
	&lt;dt&gt;List available&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;ls /usr/local/Library/Formula/&lt;/tt&gt;&lt;/dd&gt;
	&lt;dt&gt;List installed&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;ls /usr/local/Cellar/&lt;/tt&gt;&lt;/dd&gt;
	&lt;dt&gt;Info&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;brew info git&lt;/tt&gt;&lt;/dd&gt;
	&lt;dt&gt;Create formula&lt;/dt&gt;
	&lt;dd&gt;&lt;tt&gt;brew make http://url.com/to/something-2.2.tar.gz&lt;/tt&gt;. Yes, it&amp;#8217;s that easy.&lt;/dd&gt;
&lt;/dl&gt;
&lt;h2&gt;You shouldn&amp;#8217;t use sudo&lt;/h2&gt;
&lt;p&gt;Brew suggests you install it to &lt;tt&gt;/usr/local&lt;/tt&gt;, and promptly chmod &lt;tt&gt;/usr/local&lt;/tt&gt; so that you have permissions to it. That makes sense. Why should &lt;tt&gt;/usr/local&lt;/tt&gt; require sudo? You &lt;em&gt;can&lt;/em&gt; use sudo if you like, but unless you don&amp;#8217;t have a particular reason to do so, Homebrew suggests that you don&amp;#8217;t.&lt;/p&gt;
&lt;p&gt;Run &lt;strong&gt;&lt;tt&gt;sudo chown -R `whoami`:staff /usr/local&lt;/tt&gt;&lt;/strong&gt; to set the permissions.&lt;/p&gt;
&lt;h2&gt;Fetching new packages, updating existing.&lt;/h2&gt;
&lt;p&gt;Homebrew stores the list of packages in git. It doesn&amp;#8217;t have a &lt;tt&gt;brew update&lt;/tt&gt; command yet.&lt;/p&gt;
&lt;p&gt;Use &lt;strong&gt;steps in bold&lt;/strong&gt; only if you installed with git.&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;&lt;tt&gt;brew install git&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;&lt;tt&gt;cd /usr/local&lt;/tt&gt;&lt;/strong&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git init&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git remote add origin git://github.com/mxcl/homebrew.git&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;&lt;tt&gt;git pull origin masterbrew&lt;/tt&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;</description>
      <pubDate>Wed, 02 Sep 2009 19:48:12 GMT</pubDate>
      <guid>http://august.lilleaas.net/homebrew_is_awesome</guid>
    </item>
    
    
    <item>
      <title>S3 Upload Snow Leopard Service</title>
      <link>http://august.lilleaas.net/s3_upload_snow_leopard_service</link>
      <description>&lt;p&gt;Snow Leopard, the latest addition to the OS X family, has &lt;del&gt;a new and very powerful feature called services&lt;/del&gt; revamped the Services system, and made it a whole lot more useful. In short, services are contextual aware actions, and Apple has made it easy for users to create their own services with an updated Automator.&lt;/p&gt;
&lt;p&gt;I wanted to familiarize myself with how the services system works, and create something useful. I created a service that lets you upload documents (images, mp3s, text documents, &amp;#8230;) to an Amazon S3 bucket. Short summary:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Install&lt;/li&gt;
	&lt;li&gt;Right click image, choose &amp;#8220;Upload to S3&amp;#8221;&lt;/li&gt;
	&lt;li&gt;&lt;span class="caps"&gt;URL&lt;/span&gt; of uploaded image is pasted to your clipboard.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Awesome for sharing images on IM, email, irc, and so on.&lt;/p&gt;
&lt;p style="float:left;"&gt;&lt;img src="http://s3.amazonaws.com/augustl-stuff/upload-to-s3-contextual-menu-67.png" alt="" /&gt;&lt;/p&gt;
&lt;p style="float:left;"&gt;&lt;img src="http://s3.amazonaws.com/augustl-stuff/upload-to-s3-success-35.png" alt="" /&gt;&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;
&lt;h2&gt;Installing&lt;/h2&gt;
&lt;ol&gt;
	&lt;li&gt;Download &lt;a href="http://augustl-stuff.s3.amazonaws.com/Upload%20to%20S3%20v3.zip"&gt;the service&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;Extract and copy to &lt;tt&gt;~/Library/Services&lt;/tt&gt;. Create the directory if it doesn&amp;#8217;t exist.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That&amp;#8217;s all there is. The next time you right click an image, there&amp;#8217;ll be a &amp;#8220;Upload to S3&amp;#8221; option in the right click menu.&lt;/p&gt;
&lt;p&gt;When you run the script for the first time, you will be prompted for your S3 login credentials. Don&amp;#8217;t worry, they will be safely stored in your keychain, just like all your passwords are on OS X.&lt;/p&gt;
&lt;h2&gt;How it works&lt;/h2&gt;
&lt;p&gt;The service/Automator workflow uses a combination of Applescript and Ruby to get the job done. The applescripts handles the dialog boxes and fetches info from the keychain. The ruby script uses the aws/s3 gem to upload the file to S3. It installs the gem if it isn&amp;#8217;t already installed. When the ruby script has uploaded the file, it will pass on the &lt;span class="caps"&gt;URL&lt;/span&gt; to a 2nd applescript which pastes the &lt;span class="caps"&gt;URL&lt;/span&gt; to the clipboard and provides feedback to the user.&lt;/p&gt;
&lt;p&gt;The ability to execute ruby scripts out of the box from automator is new in Snow Leopard. So are the contextual services. Snow Leopard was released mere days ago, we can only begin to imagine the different ways people will make use of this new and powerful feature.&lt;/p&gt;
&lt;p&gt;If you want to have a look at the source code, download the service (link above) and open it with Automator.&lt;/p&gt;
&lt;h2&gt;&lt;span class="caps"&gt;CHANGELOG&lt;/span&gt;&lt;/h2&gt;
&lt;ol&gt;
	&lt;li&gt;Sep 2. 2009: Checking if the bucket name is blank when the bucket name storage file exists.&lt;/li&gt;
	&lt;li&gt;Aug 31. 2009: Updated to use &amp;#8220;documents&amp;#8221; instead of &amp;#8220;images&amp;#8221;, to enable uploading of text files, audio files, and more.&lt;/li&gt;
&lt;/ol&gt;</description>
      <pubDate>Sun, 30 Aug 2009 21:58:43 GMT</pubDate>
      <guid>http://august.lilleaas.net/s3_upload_snow_leopard_service</guid>
    </item>
    
    
    <item>
      <title>How I Would Improve That New Tv Guide</title>
      <link>http://august.lilleaas.net/how_i_would_improve_that_new_tv_guide</link>
      <description>&lt;p&gt;The twitterverse very recently made me aware of &lt;a href="http://se.no"&gt;se.no&lt;/a&gt;. It&amp;#8217;s a complete overhault of &lt;a href="http://fredag.dagbladet.no/tv/flat.html"&gt;this old TV guide&lt;/a&gt;, which is one of the most popular online TV guides in Norway.&lt;/p&gt;
&lt;p&gt;I am a big fan of the lack of flash. Dagbladet, the Norwegian newspaper owning and maintaining this TV guide, has used jQuery and jQuery UI to create their revamped guide by using &lt;span class="caps"&gt;HTML&lt;/span&gt;, &lt;span class="caps"&gt;CSS&lt;/span&gt; and Javascript. If I were to present my argument for why I prefer Javascript to Flash, I&amp;#8217;d be derailing this post and ended up with a wall of text. Short summary: I like standards and high performance. Flash is owned by Adobe, doesn&amp;#8217;t exist on the iPhone, performance is dependent on Adobe alone so the awesome and speedy Safari 4 is still slow when flash is being around, and so on and so forth.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m not here to sweettalk about se.no, though. We&amp;#8217;re on the internet, after all. I have some issues with the choices they have made when it comes to the interaction of this TV guide. More about that in a sec. First:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;a href="http://se.no/"&gt;Se.no&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href="http://august.lilleaas.net/_demo/se_alternativ/"&gt;My mockup&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That mockup is mine, and it is a demo of how I would have designed the interaction. Before you read on, open both of them and get a feel of how they work.&lt;/p&gt;
&lt;h2&gt;The scroll wheel scrolls vertically.&lt;/h2&gt;
&lt;p&gt;One of the major pillars in interaction design is that you don&amp;#8217;t want your users to be surprised. Users have habits when it comes to common and frequently used design elements, and not honoring these habits breaks the interaction.&lt;/p&gt;
&lt;p&gt;In this sense, se.no breaks the scroll wheel. The user&amp;#8217;s habit is that when a site has a vertical scroll, it can be scrolled with the scroll wheel. se.no has a vertical scroll, but using the scroll wheel makes the site scroll horizontally. In my opinion, it&amp;#8217;s only (somewhat) OK to set the scroll wheel to the horizontal scroll if no vertical scroll is present.&lt;/p&gt;
&lt;p&gt;I can certainly see why the se.no crew made the desicion they made, though. The visual layout of the TV guide is horizontally biased, and it&amp;#8217;s very logical to have the scroll wheel scrolling what is considered the main scroll on the page. Regardless, I think that &lt;em&gt;vertical scroll&lt;/em&gt; is more important than &lt;em&gt;main scroll&lt;/em&gt; for a scroll wheel, especially when there is a vertical scroll present, for the reasons mentioned above.&lt;/p&gt;
&lt;p&gt;In my mockup, you scroll horizontally by clicking and holding the main list of entries, and moving the mouse around. Regular drag and drop. This is how a scrollbar normally works, and perhaps a even better alternative would be to have a horizontal scroll bar at the bottom of the page. That was a bit hard to implement, though, so I went for the full hit are a scroll. The vertical scroll uses the normal browser scroll bar. No javascript magics whatsoever.&lt;/p&gt;
&lt;h2&gt;Smooth scrolling when dragging&lt;/h2&gt;
&lt;p&gt;On se.no, you can in fact scroll by dragging the mouse. You can scroll horizontally by dragging the black line of time-stamps on the top, and scroll vertically similar to how I scroll horizontally in my mockup (by clicking and dragging the main timeline).&lt;/p&gt;
&lt;p&gt;The scrolling isn&amp;#8217;t smooth, though. I&amp;#8217;m not talking about the subjective kind of smooth (smoooooooooth!), but the grid the scrolling on se.no is locked on to. I can&amp;#8217;t think of upsides of having a grid like that on a page like this, so I&amp;#8217;m not going to try to justify se.no&amp;#8217;s desicions here. The grid makes it harder to keep the context while scrolling, since you might loose grasp of where you are for a few moments right after you have jumped a step in the grid, and generally less pleasant to look at.&lt;/p&gt;
&lt;p&gt;In my mockup, the scrolling is smooth (both subjective and objective).&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;When it comes to interaction design, you don&amp;#8217;t want to re-invent the wheel. Messing with users preconceived habits and expectations makes it hard to interact with your product. Your goal should be to create an easy interaction, and you do this by giving users what they actually expect, not what they ought to expectfrom a logical standpoint. If amazon.com uses tabs a way tabs shouldn&amp;#8217;t be used from a logical standpoint, you should too.&lt;/p&gt;</description>
      <pubDate>Fri, 14 Aug 2009 17:00:02 GMT</pubDate>
      <guid>http://august.lilleaas.net/how_i_would_improve_that_new_tv_guide</guid>
    </item>
    
    
    <item>
      <title>Pluginized Jquery Google Maps</title>
      <link>http://august.lilleaas.net/pluginized_jquery_google_maps</link>
      <description>&lt;p&gt;In &lt;a href="/unobtrusive_google_maps_with_jquery"&gt;my recent article on dynamically loading interactive Google maps on top of static maps&lt;/a&gt;, I wrote a whole lot un-idiomatic jQuery code. That doesn&amp;#8217;t matter, because the article was about fast page loads and fancy techniques, not jQuery conventions.&lt;/p&gt;
&lt;p&gt;I do like to follow conventions, though, which is why I created &lt;a href="http://github.com/augustl/unobtrusive-google-maps/tree"&gt;a jQuery plugin for loading interactive Google maps on top of static maps&lt;/a&gt;. It is basically the same code as in the article, but is a lot easier to drop-in and use in your project (install a plugin instead of copy/pasting code from a web page). It is also maintained and kept up to date, which the article should be too but that&amp;#8217;s in an ideal world where people don&amp;#8217;t have green avatars and everyone uses ruby 1.9.&lt;/p&gt;
&lt;p&gt;Oh crap, this just became a politically charged post. Please forget about that and click the Github link, kktnx.&lt;/p&gt;</description>
      <pubDate>Sat, 27 Jun 2009 05:54:26 GMT</pubDate>
      <guid>http://august.lilleaas.net/pluginized_jquery_google_maps</guid>
    </item>
    
    
    <item>
      <title>Unobtrusive Google Maps With Jquery</title>
      <link>http://august.lilleaas.net/unobtrusive_google_maps_with_jquery</link>
      <description>&lt;p&gt;Google Maps is a great tool for displaying maps on webpages. Using them on your page doesn&amp;#8217;t come without a price, though. Typically, you want a webpage to have finished loading in about 200-300 milliseconds. Loading a Google map can take up to a second, effectively tripling the load time of your page.&lt;/p&gt;
&lt;p&gt;This article is about keeping your page speedy when you use Google Maps, avoiding the long page load times you&amp;#8217;ll get with vanilla Google Maps integrations.&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s the final result we&amp;#8217;re aiming for. A static map that, when clicked, loads a interactive map. Why this is a good thing is explained in the article below.&lt;/p&gt;
&lt;p&gt;Click the map!&lt;/p&gt;
&lt;p&gt;&lt;img src="http://maps.google.com/staticmap?center=40.714728,-73.998672&amp;amp;zoom=13&amp;amp;size=500x300&amp;amp;maptype=mobile&amp;amp;markers=40.714728,-73.998672&amp;amp;sensor=false&amp;amp;key=ABQIAAAAXYawz0HUhQEfK4yV1l2SWxQqCyHoT6LEDbPCa7oX2Mha8N4j1RSNHHsyBLVjnkvsR4rLjrpwwQWLKA" id="map" /&gt;&lt;/p&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
  type="text/javascript"&gt;&lt;/script&gt;&lt;script&gt;
  window.UnobtrusiveGoogleMaps = {
    initialize: function(selector){
      this.targetDomObject = $(selector);
      this.targetDomObject.click(function(){
        UnobtrusiveGoogleMaps.loadInteractiveMap();
      });
      
      this.options = this.getOptionsFromQueryParameters();
    },
    
    getOptionsFromQueryParameters: function(){
      var src = this.targetDomObject.attr("src");
      var options = {}
      var queryParameters = {};
      $.each(/\?(.+)/.exec(src)[1].split("&amp;"), function(i, x) {
        var r = x.split("="); queryParameters[r[0]] = r[1];
      });
      
      options.zoom = parseInt(queryParameters["zoom"]);

      var sizes = queryParameters["size"].split("x");
      options.width = parseInt(sizes[0]);
      options.height = parseInt(sizes[1]);

      var latLong = queryParameters["center"].split(",");
      options.latitude = parseFloat(latLong[0]);
      options.longitude = parseFloat(latLong[1]);
      
      return options;
    },
    
    loadInteractiveMap: function(){
      var url = [
        "http://maps.google.com/maps/api/js?",
        "sensor=false",
        "&amp;callback=UnobtrusiveGoogleMaps.googleMapsLibraryLoaded"
      ];

      $.getScript(url.join(""));
    },
    
    googleMapsLibraryLoaded: function(){
      var target = $(document.createElement("div"));
      target.css({width: this.options.width, height: this.options.height});
      this.targetDomObject.replaceWith(target);
      
      var point = new google.maps.LatLng(this.options.latitude, this.options.longitude);
      var map = new google.maps.Map(target[0], {
        zoom: this.options.zoom, center: point,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      new google.maps.Marker({position: point, map: map });
    }
  }

  $(function(){
    UnobtrusiveGoogleMaps.initialize("#map");
  });
&lt;/script&gt;&lt;p&gt;&lt;a href="/_demo/unobtrusive_google_maps.html" target="_blank"&gt;Open in a new window&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Update: the plugin&lt;/h2&gt;
&lt;p&gt;I created a pluginized version of this code. It&amp;#8217;s available &lt;a href="http://github.com/augustl/unobtrusive-google-maps/tree"&gt;here, on Github&lt;/a&gt;. Because installing a plugin is much better than copy/pasting text from a web page. Read the article, though, so that you grok why you should use this plugin in the first place.&lt;/p&gt;
&lt;h2&gt;Using the Static Google Maps &lt;span class="caps"&gt;API&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Since the main goal of showing a map is to show a map, all you really need to do that is a flat &lt;span class="caps"&gt;JPEG&lt;/span&gt;. That is exactly what the Static Google Maps &lt;span class="caps"&gt;API&lt;/span&gt; provides: A flat &lt;span class="caps"&gt;JPEG&lt;/span&gt; version of their interactive maps.&lt;/p&gt;
&lt;pre&gt;&amp;lt;img src="http://maps.google.com/staticmap?center=40.714728,-73.998672&amp;amp;amp;zoom=13\
&amp;amp;amp;size=500x300&amp;amp;amp;maptype=mobile&amp;amp;amp;markers=40.714728,-73.998672\
&amp;amp;amp;sensor=false&amp;amp;amp;key=MAPS_API_KEY" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src="http://maps.google.com/staticmap?center=40.714728,-73.998672&amp;amp;zoom=13&amp;amp;size=500x300&amp;amp;maptype=mobile&amp;amp;markers=40.714728,-73.998672&amp;amp;sensor=false&amp;amp;key=ABQIAAAAXYawz0HUhQEfK4yV1l2SWxQqCyHoT6LEDbPCa7oX2Mha8N4j1RSNHHsyBLVjnkvsR4rLjrpwwQWLKA" /&gt;&lt;/p&gt;
&lt;p&gt;One single image loads way faster than the javascript and image heavy interactive Google maps.&lt;/p&gt;
&lt;p&gt;Obviously, you can&amp;#8217;t pan and zoom this flat &lt;span class="caps"&gt;JPEG&lt;/span&gt;. So what do we do in order to get the best from both worlds; fast load times and interactive maps?&lt;/p&gt;
&lt;h2&gt;Loading interactive maps on demand&lt;/h2&gt;
&lt;p&gt;The first thing a user does with a map is to look at it. At this time in the interaction, you don&amp;#8217;t need a pannable and zoomable map. The abiliy to pan and zoom is not required until the user actually clicks on the map, attempting to perform these operations.&lt;/p&gt;
&lt;p&gt;Loading the interactive map on demand means loading it at this time; when the user clicks the static map. When this happens, it is replaced with a interactive map.&lt;/p&gt;
&lt;p&gt;This interaction flow is a big win. Your page will load faster, because displaying images is faster than loading interactive Google maps. Clicking the map isn&amp;#8217;t something users want or can do until the page has loaded completely anyway, and some users might not want to browse an interactive map at all. Holding back the interactive maps untill they are needed makes sense in a lot of cases.&lt;/p&gt;
&lt;h2&gt;Implementing&lt;/h2&gt;
&lt;p&gt;We need to hook the click event of the image. In this event, we need to load the Google Maps javascripts, and replace the image with a div that contains the interactive map.&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s a basic skeleton:&lt;/p&gt;
&lt;pre&gt;// Only a skeleton!
  
window.googleMapsLibraryLoaded = function(){
  var target = $(document.createElement("div")).css({width: 500, height: 250});
  $("#map").replaceWith(target);

  var point = new google.maps.LatLng(40.714728, -73.998672);
  var map = new google.maps.Map(target[0], {
    zoom: 13, center: point,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  new google.maps.Marker({position: point, map: map});
}

$("img#map").click(function(){
  var url = [
    "http://maps.google.com/maps/api/js?",
    "sensor=false",
    "&amp;amp;callback=googleMapsLibraryLoaded"
  ]

  $.getScript(url.join(""));
});&lt;/pre&gt;
&lt;p&gt;In the click event of the image, &lt;code&gt;$.getScript&lt;/code&gt; loads the external Google Maps scripts .The &lt;tt&gt;callback&lt;/tt&gt; parameter contains the name of our function, &lt;code&gt;googleMapsLibraryLoaded&lt;/code&gt;. When the Google Maps scripts has finished initializing, it will call this callback function. In this callback, we replace the image with a new div that contains the interactive Google map.&lt;/p&gt;
&lt;h2&gt;Using the data from the image to load the map&lt;/h2&gt;
&lt;p&gt;In the basic implementation above, the longitude, latitude, map size and zoom level is duplicated in the scripts. A sensible implementation would use the data already provided by the static image. The &lt;span class="caps"&gt;URL&lt;/span&gt; to the image (the &lt;code&gt;src&lt;/code&gt; attribute) contains all these parameters, and since we are good unobtrusive javascript citizens, we will use these parameters in our javascripts instead of passing it on via &lt;code&gt;&amp;lt;script&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
&lt;p&gt;The full &lt;span class="caps"&gt;URL&lt;/span&gt; is just a string, so we will have to parse it. This adds some overhead, but not too much to be a real problem. We will also use this opportunity to move all the code into an object which we will name &lt;code&gt;UnobtrusiveGoogleMaps&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&amp;gt;

&amp;lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&amp;gt;
  &amp;lt;title&amp;gt;Unobtrusive Google Maps&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  
  &amp;lt;img src="http://maps.google.com/staticmap?center=40.714728,-73.998672&amp;amp;amp;zoom=13&amp;amp;amp;size=500x300&amp;amp;amp;maptype=mobile&amp;amp;amp;markers=40.714728,-73.998672&amp;amp;amp;sensor=false&amp;amp;amp;key=ABQIAAAAXYawz0HUhQEfK4yV1l2SWxQqCyHoT6LEDbPCa7oX2Mha8N4j1RSNHHsyBLVjnkvsR4rLjrpwwQWLKA" id="map" /&amp;gt;
  
  &amp;lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
    type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    window.UnobtrusiveGoogleMaps = {
      initialize: function(selector){
        this.targetDomObject = $(selector);
        this.targetDomObject.click(function(){
          UnobtrusiveGoogleMaps.loadInteractiveMap();
        });
        
        this.options = this.getOptionsFromQueryParameters();
      },
      
      getOptionsFromQueryParameters: function(){
        var src = this.targetDomObject.attr("src");
        var options = {}
        var queryParameters = {};
        $.each(/\?(.+)/.exec(src)[1].split("&amp;amp;"), function(i, x) {
          var r = x.split("="); queryParameters[r[0]] = r[1];
        });
        
        options.zoom = parseInt(queryParameters["zoom"]);

        var sizes = queryParameters["size"].split("x");
        options.width = parseInt(sizes[0]);
        options.height = parseInt(sizes[1]);

        var latLong = queryParameters["center"].split(",");
        options.latitude = parseFloat(latLong[0]);
        options.longitude = parseFloat(latLong[1]);
        
        return options;
      },
      
      loadInteractiveMap: function(){
        var url = [
          "http://maps.google.com/maps/api/js?",
          "sensor=false",
          "&amp;amp;callback=UnobtrusiveGoogleMaps.googleMapsLibraryLoaded"
        ];

        $.getScript(url.join(""));
      },
      
      googleMapsLibraryLoaded: function(){
        var target = $(document.createElement("div"));
        target.css({width: this.options.width, height: this.options.height});
        this.targetDomObject.replaceWith(target);
        
        var point = new google.maps.LatLng(this.options.latitude, this.options.longitude);
        var map = new google.maps.Map(target[0], {
          zoom: this.options.zoom, center: point,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        new google.maps.Marker({position: point, map: map });
      }
    }
  
    $(function(){
      UnobtrusiveGoogleMaps.initialize("#map");
    });
  &amp;lt;/script&amp;gt;
  
  &amp;lt;script type="text/javascript"&amp;gt;
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  &amp;lt;/script&amp;gt;
  &amp;lt;script type="text/javascript"&amp;gt;
  try {
  var pageTracker = _gat._getTracker("UA-9100016-1");
  pageTracker._trackPageview();
  } catch(err) {}&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;window.UnobtrusiveGoogleMaps&lt;/code&gt; makes it a global variable. &lt;code&gt;UnobtrusiveGoogleMaps&lt;/code&gt; alone would also be a global variable, but I prefer to be explicit about it, so that it is obvious that it is global, and I didn&amp;#8217;t just forget to add a &lt;code&gt;var&lt;/code&gt; in front of it.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;googleMapsLibraryLoaded&lt;/code&gt; gets it&amp;#8217;s data from &lt;code&gt;this.options&lt;/code&gt; instead of being hardcoded. &lt;code&gt;this.options&lt;/code&gt; contains the values parsed out of the static map image&amp;#8217;s &lt;span class="caps"&gt;URL&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;That is all there is to it!&lt;/p&gt;
&lt;p&gt;&lt;a href="/_demo/unobtrusive_google_maps.html" target="_blank"&gt;Check out the working finished example!&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 26 Jun 2009 15:22:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/unobtrusive_google_maps_with_jquery</guid>
    </item>
    
    
    <item>
      <title>Global Gitignores</title>
      <link>http://august.lilleaas.net/global_gitignores</link>
      <description>&lt;p&gt;On Mac OS X, the Finder creates a &lt;tt&gt;.DS_Store&lt;/tt&gt; file in all the directories it displays. If you happen to browse your git repository with the Finder, you&amp;#8217;ll get these files in your repo, and they&amp;#8217;ll show up as untracked files in &lt;tt&gt;git status&lt;/tt&gt;. A common workaround is to add &lt;tt&gt;.DS_Store&lt;/tt&gt; to the &lt;tt&gt;.gitignore&lt;/tt&gt;. Here&amp;#8217;s one of my gitignore files for a Rails project:&lt;/p&gt;
&lt;pre&gt;.DS_Store
*.log
*.sqlite3
config/database.yml
db/schema.rb
tmp/**/*&lt;/pre&gt;
&lt;p&gt;I have a slight problem with this, though. The &lt;tt&gt;.DS_Store&lt;/tt&gt; isn&amp;#8217;t related to your project, it is related to the system you&amp;#8217;re coding on. Yor &lt;tt&gt;.gitignore&lt;/tt&gt; file will be a lot more elegant if it only lists files that are related to the projects. For a Rails app, log files and &lt;tt&gt;db/schema.rb&lt;/tt&gt; is definitely app related. &lt;tt&gt;.DS_Store&lt;/tt&gt; isn&amp;#8217;t, though.&lt;/p&gt;
&lt;p&gt;This is why I have a global gitignore file for my system, that ignores system related files.&lt;/p&gt;
&lt;pre&gt;&amp;gt; git config --global core.excludefiles ~/.gitignore&lt;/pre&gt;
&lt;p&gt;This file contains the following:&lt;/p&gt;
&lt;pre&gt;.DS_Store&lt;/pre&gt;
&lt;p&gt;And voila, you no longer have to add &lt;tt&gt;.DS_Store&lt;/tt&gt; to all your &lt;tt&gt;.gitignore&lt;/tt&gt; files.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;While this article might seem OS X specific, it applies to all systems. A good example is &lt;tt&gt;thumbs.db&lt;/tt&gt; on Windows systems. I&amp;#8217;m sure some Linux distros has similar system files. Global gitignores are not limited to &lt;tt&gt;.DS_Store&lt;/tt&gt; on OS X, but all system files that shouldn&amp;#8217;t be allowed to sneak into your repositories or your &lt;tt&gt;.gitignore&lt;/tt&gt;s.&lt;/p&gt;</description>
      <pubDate>Thu, 25 Jun 2009 08:00:17 GMT</pubDate>
      <guid>http://august.lilleaas.net/global_gitignores</guid>
    </item>
    
    
    <item>
      <title>Time Calculations In Javascript</title>
      <link>http://august.lilleaas.net/time_calculations_in_javascript</link>
      <description>&lt;p&gt;I just released JS-Time! &lt;a href="http://github.com/augustl/js-time/tree"&gt;http://github.com/augustl/js-time/tree&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;JS-Time is a javascript library for performing time calculations. It is completely framework agnostic, so you can easily drop it to any existing project already jQuery, Prototype, Motools, or something else. The tests are passing on IE6 to 8, Firefox, Opera and Safari.&lt;/p&gt;
&lt;pre&gt;new Time(2008, 5, 17);
time.month() // 5

new Time(2006, 1, 30).advanceMonths(1).day()      // 28 (February 28th)
new Time(2008, 5, 17).beginningOfYear()           // January 1st 2008
new Time(2008, 5, 17, 22, 30).beginningOfDay()    // May 17th 2008, 00:00
new Time(2008, 5, 17, 16, 30).endOfHour()         // May 5th 2008, 16:59

new Time(2008, 1).firstDayInCalendarMonth()       // December 30th 2007
new Time(1804).isLeapYear(); // true
new Time(2008, 2).weeksInMonth()                  // 5
new Time(2008, 1).daysInMonth();                  // 31&lt;/pre&gt;
&lt;p&gt;You can set the first day of the week with &lt;code&gt;Time.firstDayOfWeek = 2&lt;/code&gt;. It defaults to 1, Sunday.&lt;/p&gt;
&lt;p&gt;Please &lt;a href="http://github.com/augustl/js-time/issues"&gt;let me know&lt;/a&gt; if you encounter any problems.&lt;/p&gt;</description>
      <pubDate>Sat, 20 Jun 2009 20:48:57 GMT</pubDate>
      <guid>http://august.lilleaas.net/time_calculations_in_javascript</guid>
    </item>
    
    
    <item>
      <title>Styling Rails Urls</title>
      <link>http://august.lilleaas.net/styling_rails_urls</link>
      <description>&lt;p&gt;This article explains how you can alter the looks of your URLs in a Rails friendly way. I assume that you know how to use &lt;code&gt;map.resources&lt;/code&gt; and named routes.&lt;/p&gt;
&lt;h2&gt;Adding .html to all pages&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;ActionController&lt;/code&gt; has a &lt;code&gt;default_url_options&lt;/code&gt; method that it uses for all &lt;span class="caps"&gt;URL&lt;/span&gt; generation tasks. It returns an empty hash by default, but can be overridden.&lt;/p&gt;
&lt;pre&gt;class ApplicationController &amp;lt; ActionController::Base
  def default_url_options(options = nil)
    {:format =&amp;gt; "html"}
  end
end&lt;/pre&gt;
&lt;p&gt;Note that the options to your individual route calls gets predesence, &lt;code&gt;posts_path(:format =&amp;gt; "xml")&lt;/code&gt; will append &lt;tt&gt;.xml&lt;/tt&gt;, not &lt;tt&gt;.html&lt;/tt&gt;.&lt;/p&gt;
&lt;h2&gt;Custom route names&lt;/h2&gt;
&lt;p&gt;For a projects controller&amp;#8217;s show action, the default &lt;span class="caps"&gt;URL&lt;/span&gt; looks like this:&lt;/p&gt;
&lt;pre&gt;/projects/5&lt;/pre&gt;
&lt;p&gt;What if you want to localize it?&lt;/p&gt;
&lt;pre&gt;/prosjekter/5&lt;/pre&gt;
&lt;p&gt;One way is to name the controller &amp;#8220;prosjekter&amp;#8221; instead of &amp;#8220;projects&amp;#8221;. That isn&amp;#8217;t very Rails friendly, though, you&amp;#8217;ll end up fighting with pluralization conventions. Thankfully, there is a Rails friendly way to do this, via &lt;tt&gt;routes.rb&lt;/tt&gt;.&lt;/p&gt;
&lt;pre&gt;map.resources :projects, :as =&amp;gt; "prosjekter", :path_names =&amp;gt; {:new =&amp;gt; "nytt", :edit =&amp;gt; "rediger"}&lt;/pre&gt;
&lt;p&gt;That will give you these URLs:&lt;/p&gt;
&lt;pre&gt;/prosjekter/5
/prosjekter/nytt
/prosjekter/5/rediger&lt;/pre&gt;
&lt;p&gt;You can also set &lt;code&gt;:path_names&lt;/code&gt; globally, by adding the following to &lt;tt&gt;config/environment.rb&lt;/tt&gt;.&lt;/p&gt;
&lt;pre&gt;config.action_controller.resources_path_names = { :new =&amp;gt; 'ny', :edit =&amp;gt; 'rediger' }&lt;/pre&gt;
&lt;h2&gt;URLs without the ID of the record&lt;/h2&gt;
&lt;p&gt;Normaly, Rails URLs look like this:&lt;/p&gt;
&lt;pre&gt;/posts/5
/projects/239
/users/39/favorites/2&lt;/pre&gt;
&lt;p&gt;Perhaps you want more descriptive URLs, though, such as having the title of the post in the &lt;span class="caps"&gt;URL&lt;/span&gt; instead of just the ID. Here are a few altervatives.&lt;/p&gt;
&lt;h2&gt;The easy way with compromises&lt;/h2&gt;
&lt;pre&gt;/posts/5-a-post-about-rockets
/projects/239-new-website
/users/39-augustl/favorites/2-that-book&lt;/pre&gt;
&lt;p&gt;The compromise is that the ID still is in the &lt;span class="caps"&gt;URL&lt;/span&gt;. It is unlikely that a visible ID is a problem, but if it for some reason is, you can learn how to do it without the ID in the next section.&lt;/p&gt;
&lt;p&gt;What makes Rails use the ID alone in the first place? The answer is &lt;code&gt;to_param&lt;/code&gt;. It&amp;#8217;s an instance method in all models, and it looks like this:&lt;/p&gt;
&lt;pre&gt;def to_param
  id
end&lt;/pre&gt;
&lt;p&gt;We can override it to include the title of the post as well as the ID.&lt;/p&gt;
&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base
  def to_param
    "#{id}-#{title.parameterize}"
  end
end&lt;/pre&gt;
&lt;p&gt;Rails will now use the id, a dash, and and &lt;span class="caps"&gt;URL&lt;/span&gt; friendly version of the title. We need to make it &lt;span class="caps"&gt;URL&lt;/span&gt; friendly with &lt;code&gt;parameterize&lt;/code&gt;, so that &lt;code&gt;"Foo and bar!"&lt;/code&gt; turns into &lt;code&gt;"foo-and-bar"&lt;/code&gt;. If we don&amp;#8217;t, we&amp;#8217;ll get invalid URLs, and browsers will blow up.&lt;/p&gt;
&lt;p&gt;The reason this is the easy way, is that this is all there is to it. Our finds will still work, because of the way Ruby handles &lt;code&gt;to_i&lt;/code&gt; on strings.&lt;/p&gt;
&lt;pre&gt;"5-a-post-about-rockets".to_i
# =&amp;gt; 5&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;find&lt;/code&gt; method that we use in the controllers calls &lt;code&gt;to_i&lt;/code&gt; for us.&lt;/p&gt;
&lt;pre&gt;Post.find("5-a-post-about-rockets")
# equals
Post.find(5)&lt;/pre&gt;
&lt;h2&gt;The hard way&lt;/h2&gt;
&lt;pre&gt;/posts/a-post-about-rockets
/projects/new-website
/users/augustl/favorites-that-book&lt;/pre&gt;
&lt;p&gt;Because the ID is no longer in the &lt;span class="caps"&gt;URL&lt;/span&gt;, we have to change the code a bit.&lt;/p&gt;
&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base
  before_create :create_slug
  
  def to_param
    slug
  end
    
  def create_slug
    self.slug = self.title.parameterize
  end
end&lt;/pre&gt;
&lt;p&gt;When a post is created, the &lt;span class="caps"&gt;URL&lt;/span&gt; friendly version of the title is stored in the database, in the &lt;tt&gt;slug&lt;/tt&gt; column. We also have to update the finds to find records using the slug column instead of using the ID.&lt;/p&gt;
&lt;pre&gt;class ProjectsController &amp;lt; ApplicationController
  def show
    @project = Project.find_by_slug!(params[:id])
  end
end&lt;/pre&gt;
&lt;p&gt;Apply the same tactic to all relevant finds, and you&amp;#8217;re good to go.&lt;/p&gt;
&lt;h2&gt;No controller names&lt;/h2&gt;
&lt;p&gt;Instead of &lt;code&gt;/users/augustl/projects/a-project&lt;/code&gt;, you might prefer this:&lt;/p&gt;
&lt;pre&gt;/augustl/a-project
/some-user/another-project&lt;/pre&gt;
&lt;p&gt;Just a heads up: Most people don&amp;#8217;t care about how the URLs looks. In my opinion, it only makes sense to do this kind of routing if your users are typing in the URLs by hand, or if the &lt;span class="caps"&gt;URL&lt;/span&gt; is commonly linked to. Github projects is a good example of sensible use of short URLs. If not, I advise you to leave the controller names in there.&lt;/p&gt;
&lt;p&gt;Anyhow, here&amp;#8217;s how you do it:&lt;/p&gt;
&lt;pre&gt;map.short_user ":id", :controller =&amp;gt; "users", :action =&amp;gt; "show"
map.short_project ":user_id/:id", :controller =&amp;gt; "projects", :action =&amp;gt; "show"&lt;/pre&gt;
&lt;p&gt;This gives you two very handy named routes.&lt;/p&gt;
&lt;pre&gt;short_user_path(@user)
short_project_path(@user, @project)&lt;/pre&gt;
&lt;p&gt;The example above only handles those two show actions. I advise using regular &lt;code&gt;map.resources&lt;/code&gt; for &lt;code&gt;create&lt;/code&gt;, &lt;code&gt;edit&lt;/code&gt; etc. Users will never have to &lt;em&gt;link&lt;/em&gt; to the &lt;span class="caps"&gt;URL&lt;/span&gt; that creates a new project, so it&amp;#8217;s pointless to style those routes.&lt;/p&gt;</description>
      <pubDate>Sun, 14 Jun 2009 21:06:44 GMT</pubDate>
      <guid>http://august.lilleaas.net/styling_rails_urls</guid>
    </item>
    
    
    <item>
      <title>Option Hash Fetishes</title>
      <link>http://august.lilleaas.net/option_hash_fetishes</link>
      <description>&lt;p&gt;I love to write code! I also like being in control of my code and it&amp;#8217;s end result. This often leads me to write everything from scratch. Too many plugins have an option hash fetish, rendering me unable to do things the way I want to do them.&lt;/p&gt;
&lt;p&gt;So why do I use Rails, you say? Because option hashes are fine as long as it&amp;#8217;s on a low enough level. &lt;code&gt;has_many&lt;/code&gt; using an option hash makes perfect sense. I don&amp;#8217;t care how it works, so an option hash is sufficient. I do however really care how the flow of signing up works, and how the UI looks and feels. That is why I never use restful authentication and jQuery UI. They are option hash mongers.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m not saying that nobody should use restful authentication or jQuery UI. If that&amp;#8217;s what you want, then fine. Far beyond on the other side, we have &lt;a href="http://ediblepet.net/2009/05/23/web-applications-should-be-compile/"&gt;people that wants to write their webapps in C&lt;/a&gt;. It&amp;#8217;s all about how much control you want to have, and is willing to give away. Deciding how high and low level you want stuff to be is your call.&lt;/p&gt;
&lt;p&gt;My call is at the level of the user interaction. I want to be in complete control of that. I don&amp;#8217;t mind writing some code in order to be able to customize what I want to be able to customize.&lt;/p&gt;
&lt;p&gt;Which is why I wrote &lt;a href="http://github.com/augustl/authenticish/tree"&gt;Authenticish&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; Even though it&amp;#8217;s kind of off topic, I&amp;#8217;ll mention it. I wasn&amp;#8217;t aware of &lt;a href="http://github.com/binarylogic/authlogic/tree"&gt;Authlogic&lt;/a&gt;. It&amp;#8217;s awesome, and is exactly the kind of library I like to use.&lt;/p&gt;</description>
      <pubDate>Sat, 13 Jun 2009 09:37:43 GMT</pubDate>
      <guid>http://august.lilleaas.net/option_hash_fetishes</guid>
    </item>
    
    
    <item>
      <title>Combining Named Scopes</title>
      <link>http://august.lilleaas.net/combining_named_scopes</link>
      <description>&lt;p&gt;Named scopes are awesome. First, short recap of named scopes.&lt;/p&gt;
&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base
  belongs_to :author
  
  named_scope :published, :conditions =&amp;gt; {:published =&amp;gt; true}
  named_scope :ordered, :order =&amp;gt; "created_at DESC"
  named_scope :with_author, :include =&amp;gt; [:author]
end&lt;/pre&gt;
&lt;p&gt;The scopes are invoked through chainable class methods.&lt;/p&gt;
&lt;pre&gt;Post.published
Post.published.count
Post.published.ordered.with_author.each {|p| ... }&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;ActiveRecord&lt;/code&gt; doesn&amp;#8217;t have any functionality for grouping scopes, though. That can be useful in some cases, e.g creating a &lt;code&gt;orderly&lt;/code&gt; scope that is a combination of &lt;code&gt;published&lt;/code&gt; and &lt;code&gt;ordered&lt;/code&gt;. Adding that functionality is trivial, here&amp;#8217;s the monkey patch:&lt;/p&gt;
&lt;pre&gt;class ActiveRecord::Base
  def self.named_scopes(name, &amp;amp;block)
    metaclass.send(:define_method, name) {|*args| block.call(*args) }
  end
end&lt;/pre&gt;
&lt;p&gt;If you&amp;#8217;re unsure where to put this code, read and understand my &lt;a href="http://august.lilleaas.net/extending_ruby_and_rails"&gt;Extending Ruby and Rails&lt;/a&gt; article.&lt;/p&gt;
&lt;p&gt;We can now do &lt;code&gt;named_scopes(:orderly) { ordered.published.with_author }&lt;/code&gt;. The scope can be called like any other scope, e.g. &lt;code&gt;Post.orderly.count&lt;/code&gt;. Here&amp;#8217;s a real-ish example:&lt;/p&gt;
&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base
  belongs_to :author
  
  named_scope :published, :conditions =&amp;gt; {:published =&amp;gt; true}
  named_scope :ordered, :order =&amp;gt; "created_at DESC"
  named_scope :with_author, :include =&amp;gt; [:author]
  named_scope :by_author, lambda {|author| {:conditions =&amp;gt; {:author_id =&amp;gt; author.id}} }
  
  named_scopes(:orderly) { ordered.published }
  named_scopes(:for_author) {|author| ordered.published.by_author(author) }
end

Post.orderly.count
Post.for_author(an_author).with_author.each {|a| ... }&lt;/pre&gt;
&lt;h2&gt;A brief explanation of the implementation&lt;/h2&gt;
&lt;p&gt;It piggybacks heavily on the existing named scopes implementation. Because named scopes are chainable, we don&amp;#8217;t have to implement anything. The code just executes the method calls in the block passed to &lt;code&gt;named_scopes&lt;/code&gt; in the class scope. That is the equivalent of calling the methods explicitly on the class.&lt;/p&gt;
&lt;p&gt;For your information, &lt;code&gt;metaclass.send(:define_method, "foo") { ... }&lt;/code&gt; is metaprogramming for defining class methods.&lt;/p&gt;</description>
      <pubDate>Mon, 08 Jun 2009 20:28:27 GMT</pubDate>
      <guid>http://august.lilleaas.net/combining_named_scopes</guid>
    </item>
    
    
    <item>
      <title>Deadlier And Simpler Rails Deployment</title>
      <link>http://august.lilleaas.net/deadlier_and_simpler_rails_deployment</link>
      <description>&lt;p class="smaller"&gt;Disclaimer: In order to satisfy the masses, &amp;#8220;Rails&amp;#8221; is in the title of this article. The article is really about deploying through Github&amp;#8217;s post receive hooks, though, so it applies to Rails, &lt;a href="http://www.sinatrarb.com/"&gt;Sinatra&lt;/a&gt;, &lt;a href="http://github.com/why/camping/tree"&gt;Camping&lt;/a&gt;, &lt;span class="caps"&gt;PHP&lt;/span&gt; apps, or whatever.&lt;/p&gt;
&lt;p&gt;Capistrano is huge. However, even though this article is about not using Capistrano, I would like to emphasize that I don&amp;#8217;t think you should scrap Capistrano alltogether. Capistrano has a ton of sensible use cases.&lt;/p&gt;
&lt;p&gt;An example: At work, we have a Rails app that processes &lt;span class="caps"&gt;SMS&lt;/span&gt; and &lt;span class="caps"&gt;MMS&lt;/span&gt; messages from an asynchronous queue. We don&amp;#8217;t want that Rails app to be down, because that means people won&amp;#8217;t receive their &lt;span class="caps"&gt;SMS&lt;/span&gt; and &lt;span class="caps"&gt;MMS&lt;/span&gt; messages. Because of the realtime nature of &lt;span class="caps"&gt;SMS&lt;/span&gt; and &lt;span class="caps"&gt;MMS&lt;/span&gt;, being down is nasty. So, we use Capistrano to deploy, because Capistrano makes deployment less error prone. For instance, it is awesome to be able to rollback failed deploys with a single command.&lt;/p&gt;
&lt;p&gt;For smaller apps, though. I find Capistrano vastly overkill. I never use the rollback functionality. All I do is &lt;span class="caps"&gt;SSH&lt;/span&gt;-ing into the server, &lt;tt&gt;git pull&lt;/tt&gt;-ing, and restarting passenger. &lt;span class="caps"&gt;SSH&lt;/span&gt;-ing is not that elegant, though. Apparently, &lt;a href="http://tomcopeland.blogs.com/juniordeveloper/2009/05/less-php-more-ruby.html"&gt;Zed Shaw said &amp;quot;if you&amp;#8217;re SSH&amp;#8217;ing into a machine more than once a week you&amp;#8217;re doing it wrong.&amp;quot;&lt;/a&gt;. I strongly agree with that.&lt;/p&gt;
&lt;p&gt;This page is definitely a &amp;#8220;smaller app&amp;#8221;. The content is plain text files, version controlled with Git. When I deploy, I&amp;#8217;d normally &lt;span class="caps"&gt;SSH&lt;/span&gt; to the server, &lt;tt&gt;cd&lt;/tt&gt; to my homepage, &lt;tt&gt;git pull&lt;/tt&gt; and then &lt;tt&gt;touch tmp/restart.txt&lt;/tt&gt; in order to restart the web server.&lt;/p&gt;
&lt;p&gt;I don&amp;#8217;t do that, though.&lt;/p&gt;
&lt;h2&gt;How I deploy this page&lt;/h2&gt;
&lt;p&gt;I use &lt;a href="http://github.com/augustl/pushmaster/tree"&gt;pushmaster&lt;/a&gt;. Pushmaster utilizes Github&amp;#8217;s post receive hooks. When pushmaster is installed and configured, all I do and all you have to do in order to deploy your application is:&lt;/p&gt;
&lt;pre&gt;git push&lt;/pre&gt;
&lt;p&gt;What&amp;#8217;s the magick trick?&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;I run pushmaster (obviously) on http://pushmaster.lilleaas.net.&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;http://my:password@pushmaster.lilleaas.net/&lt;/tt&gt; is added as a post receive hook on &lt;a href="http://github.com/augustl/homepage/tree"&gt;the Github repository for this page&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;When i &lt;tt&gt;git push&lt;/tt&gt; from my local box, pushmaster will &lt;tt&gt;git pull&lt;/tt&gt; and &lt;tt&gt;touch tmp/restart.txt&lt;/tt&gt; on the server.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;It really is that simple. No more manual &lt;span class="caps"&gt;SSH&lt;/span&gt;!&lt;/p&gt;
&lt;h2&gt;How you can use pushmaster to deploy &lt;em&gt;your&lt;/em&gt; application&lt;/h2&gt;
&lt;ol&gt;
	&lt;li&gt;Deploy &lt;a href="http://github.com/augustl/pushmaster/tree"&gt;pushmaster&lt;/a&gt; on your server&lt;/li&gt;
	&lt;li&gt;Add a handler (see below).&lt;/li&gt;
	&lt;li&gt;Add pushmaster as a post receive hook in the Github repository for your application.&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;git push&lt;/tt&gt; from your local box.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Your handler will look like this:&lt;/p&gt;
&lt;pre&gt;Dir.chdir "/path/to/rails/application" do
  git "pull"
  touch 'tmp/restart.txt'
end&lt;/pre&gt;
&lt;p&gt;On Mongrel? No worries.&lt;/p&gt;
&lt;pre&gt;Dir.chdir "/path/to/rails/application" do
  git "pull"
  run "mongrel_rails cluster::restart"
end&lt;/pre&gt;
&lt;p&gt;Are you deploying a &lt;span class="caps"&gt;PHP&lt;/span&gt; app? Pushmaster handlers are ruby scripts with a small &lt;span class="caps"&gt;DSL&lt;/span&gt; added to them, and you are in a secure environment, so you can do anything you want.&lt;/p&gt;
&lt;pre&gt;run "whatever_you_want"
log "I just ran the command."

Dir.chdir "/path/to/awesome/php/app" do
  run "a_command"
  Net::HTTP.get_response(URI.parse("http://wtf.com"))
end&lt;/pre&gt;
&lt;p&gt;What about sending messages to your companies internal project manager?&lt;/p&gt;
&lt;pre&gt;require 'net/http'
require 'cgi'

url = URI::HTTP.build({
  :host =&amp;gt; "localhost", :port =&amp;gt; "5892",
  :query =&amp;gt; "num_commits=#{data["commits"].length}&amp;amp;ref=#{data["ref"]}"
})

Net::HTTP.get_response(url)&lt;/pre&gt;
&lt;h2&gt;Endless possibilities&lt;/h2&gt;
&lt;p&gt;Pushmaster is not really a deployment tool, it is a listening-to-github-post-receive-hooks tool. Because pushmaster is password protected, it also runs in a secure environment. As shown above, you don&amp;#8217;t have to limit pushmaster to re-deploy your apps only, you can use it for whatever you might come up with.&lt;/p&gt;
&lt;p&gt;How do you use pushmaster?&lt;/p&gt;</description>
      <pubDate>Mon, 01 Jun 2009 17:51:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/deadlier_and_simpler_rails_deployment</guid>
    </item>
    
    
    <item>
      <title>Extending Ruby And Rails</title>
      <link>http://august.lilleaas.net/extending_ruby_and_rails</link>
      <description>&lt;p&gt;It can be useful to add methods directly to internal Ruby and Rails classes.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s say you want to be able to calculate the average from an array of numbers. Compare these two examples:&lt;/p&gt;
&lt;pre&gt;[1, 2, 5, 8, 199].average
  
  --
  
array_average([1, 2, 5, 8, 199])&lt;/pre&gt;
&lt;p&gt;The first example is how it looks if you extend &lt;code&gt;Array&lt;/code&gt; with a &lt;code&gt;median&lt;/code&gt; method. The last example is none object oriented &amp;mdash; a helper, perhaps. Almost all rubyists will tell you the first example is more elegant. This article explains how you can do just that: extending existing classes instead of creating none-object oriented helpers.&lt;/p&gt;
&lt;h2&gt;How to extend classes, in general&lt;/h2&gt;
&lt;p&gt;So how do you add methods to existing classes? You do that simply by opening it, and adding methods, similar to how you create new classes.&lt;/p&gt;
&lt;pre&gt;class Array
  def average
    sum / length
  end
end&lt;/pre&gt;
&lt;p&gt;Despite how similar this looks to creating new classes, the &lt;code&gt;Array&lt;/code&gt; class won&amp;#8217;t be re-defined alltogether, Ruby will just add whatever you add. You can now call &lt;code&gt;.average&lt;/code&gt; on all arrays.&lt;/p&gt;
&lt;p&gt;PS: Ruby doesn&amp;#8217;t have a built-in &lt;code&gt;Array#sum&lt;/code&gt;. If you&amp;#8217;re in Rails, &lt;code&gt;ActiveSupport&lt;/code&gt; adds that method, though. If you for some reason are outside of Rails, use &lt;code&gt;inject(0) {|avg, i| avg += i }&lt;/code&gt; instead of &lt;code&gt;sum&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Adding the hooks in Rails&lt;/h2&gt;
&lt;p&gt;Back to a Rails application. We are going to place the core extensions in &lt;tt&gt;lib/ext/[class name].rb&lt;/tt&gt;. Copy the &lt;code&gt;Array#average&lt;/code&gt; implementation from above into &lt;tt&gt;lib/ext/array.rb&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;That is not enough, though. The file will have to execute in order to add the method to &lt;code&gt;Array&lt;/code&gt;, but it won&amp;#8217;t execute because files in &lt;tt&gt;lib/&lt;/tt&gt; aren&amp;#8217;t executed when you boot the app. They are just added to the load path (&lt;a href="http://august.lilleaas.net/where_to_put_those_codes"&gt;more here&lt;/a&gt;). The files in &lt;tt&gt;config/initializers/&lt;/tt&gt;, however, executes when the app boots, so we&amp;#8217;ll add this code snippet to an initializer (such as &lt;tt&gt;config/initializers/extensions.rb&lt;/tt&gt;) to make the files in &lt;tt&gt;lib/ext/&lt;/tt&gt; execute as well:&lt;/p&gt;
&lt;pre&gt;Dir[File.join(Rails.root, 'lib', 'ext', '**', '*.rb')].each {|ext| require ext }&lt;/pre&gt;
&lt;p&gt;Rails will now execute (require) every file in &lt;tt&gt;lib/ext/&lt;/tt&gt; when it boots.&lt;/p&gt;
&lt;h2&gt;That is all&lt;/h2&gt;
&lt;p&gt;That is everything you need in order to be able to extend Ruby and Rails core classes. Here are a few examples of how you could extend existing classes to get you started.&lt;/p&gt;
&lt;h3&gt;lib/ext/array.rb&lt;/h3&gt;
&lt;pre&gt;class Array
  def median
    if length.odd?
      self[length / 2.0]
    else
      self[(length / 2 - 1)..(length / 2)].average
    end
  end
  
  def average
    sum / length
  end
end&lt;/pre&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;pre&gt;[1, 5, 10, 32, 501, 100000].median
# =&amp;gt; 21

[1, 5, 10, 32, 100000].median
# =&amp;gt; 10&lt;/pre&gt;
&lt;h3&gt;lib/ext/active_record.rb&lt;/h3&gt;
&lt;pre&gt;class ActiveRecord::Base
  def self.case_insensitive_find(one_or_all, attribute, value)
    find(one_or_all, :conditions =&amp;gt; "LOWER(#{attribute}) = ?", value.downcase)
  end
end&lt;/pre&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;pre&gt;Author.case_insensitive_find(:all, :name, "august LiLLeAas")
Book.case_insensitive_find(:first, :title, "Hitchhikers GUIDE TO THE GALAXy")&lt;/pre&gt;
&lt;h3&gt;lib/ext/string.rb&lt;/h3&gt;
&lt;pre&gt;class String
  def randomcase
    split(//).map! {|char| rand(2) == 0 ? char.downcase : char.upcase }.join
  end
end&lt;/pre&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;pre&gt;Array.new(10) { "Hello, World!".randomcase }
  
# =&amp;gt; ["HellO, wOrLd!", "HellO, WoRLd!", "HeLLO, woRlD!", "hElLo, woRlD!", "HEllo, WoRLD!", 
"HEllo, world!", "helLO, WorLd!", "HellO, WoRld!", "Hello, woRlD!", "hElLO, wORLD!"]&lt;/pre&gt;</description>
      <pubDate>Mon, 01 Jun 2009 08:00:57 GMT</pubDate>
      <guid>http://august.lilleaas.net/extending_ruby_and_rails</guid>
    </item>
    
    
    <item>
      <title>How Rails Selects Which View To Render</title>
      <link>http://august.lilleaas.net/how_rails_selects_which_view_to_render</link>
      <description>&lt;p&gt;Rails uses a special mapping of action name and mime type to determine which template it should render.&lt;/p&gt;
&lt;pre&gt;[action_name].[mime_type].[template_type]
  
  -- or --
  
[action name].[template type]&lt;/pre&gt;
&lt;p&gt;You already know what the action name is. The &lt;span class="caps"&gt;MIME&lt;/span&gt; type and template type is usually quite confusing for newcomers, though.&lt;/p&gt;
&lt;h2&gt;Mime type&lt;/h2&gt;
&lt;p&gt;&lt;span class="caps"&gt;MIME&lt;/span&gt; types are content types or file types, such as xml, html, js and json. You specify the &lt;span class="caps"&gt;MIME&lt;/span&gt; type by appending a dot and the mime type extension to the &lt;span class="caps"&gt;URL&lt;/span&gt;, such as &lt;tt&gt;/posts.xml&lt;/tt&gt; and &lt;tt&gt;/people/5.json&lt;/tt&gt;. Since Rails usually serves &lt;span class="caps"&gt;HTML&lt;/span&gt; pages, &lt;span class="caps"&gt;HTML&lt;/span&gt; is the default mime type if none is specified, e.g. &lt;tt&gt;/posts&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;When Rails sees a &lt;span class="caps"&gt;MIME&lt;/span&gt; type in the &lt;span class="caps"&gt;URL&lt;/span&gt;, two things happen.&lt;/p&gt;
&lt;p&gt;1) It looks for a &lt;code&gt;respond_to&lt;/code&gt; block. If one is found, it calls the correct block and signs off. If there is no &lt;code&gt;respond_to&lt;/code&gt; block, the controller contiues to the next step.&lt;/p&gt;
&lt;p&gt;2) It uses the mime type to determine which view it should render, as shown in the diagram above.&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s a diagram with URLs and the view that each &lt;span class="caps"&gt;URL&lt;/span&gt; will render.&lt;/p&gt;
&lt;dl&gt;
	&lt;dt&gt;/posts&lt;/dt&gt;
	&lt;dd&gt;app/views/posts/index.html.erb&lt;/dd&gt;
	&lt;dt&gt;/users.xml&lt;/dt&gt;
	&lt;dd&gt;app/views/users/index.xml.erb&lt;/dd&gt;
	&lt;dt&gt;/projects/1.js&lt;/dt&gt;
	&lt;dd&gt;app/views/projects/show.js.erb&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;All these examples use erb as template type. This leads us to&amp;#8230;&lt;/p&gt;
&lt;h2&gt;Template types&lt;/h2&gt;
&lt;p&gt;I was lying to you earlier. Rails doesn&amp;#8217;t actually use the template type to determine which view it should render. The action name and the &lt;span class="caps"&gt;MIME&lt;/span&gt; type is all Rails needs to determine that. The purpose of the template type, not surprisingly, is to determine the template type.&lt;/p&gt;
&lt;p&gt;Here are the various template types in Rails:&lt;/p&gt;
&lt;dl&gt;
	&lt;dt&gt;ERb&lt;/dt&gt;
	&lt;dd&gt;The default template type, with &amp;lt;%= erb %&amp;gt; tags.&lt;/dd&gt;
	&lt;dt&gt;&lt;span class="caps"&gt;RJS&lt;/span&gt;&lt;/dt&gt;
	&lt;dd&gt;A &lt;span class="caps"&gt;DSL&lt;/span&gt; for generating Javascript.&lt;/dd&gt;
	&lt;dt&gt;Builder&lt;/dt&gt;
	&lt;dd&gt;A &lt;span class="caps"&gt;DSL&lt;/span&gt; for generating &lt;span class="caps"&gt;XML&lt;/span&gt;.&lt;/dd&gt;
	&lt;dt&gt;&lt;span class="caps"&gt;HAML&lt;/span&gt;&lt;/dt&gt;
	&lt;dd&gt;A 3rd party plugin, fairly common. An alternative to ERb. Google it.&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;In most cases, you will use &lt;tt&gt;.html.erb&lt;/tt&gt;, &lt;tt&gt;.js.rjs&lt;/tt&gt; or &lt;tt&gt;.xml.builder&lt;/tt&gt;. Those are the mimes these template types are designated to handle. However, any action/mime combination can use any template type, and you are free to mix and match as you like. Although most other combinations are pretty silly, there are exceptions. For example, &lt;tt&gt;.xml.erb&lt;/tt&gt; is commonly used, so that ERb generates the &lt;span class="caps"&gt;XML&lt;/span&gt; instead of Builder.&lt;/p&gt;
&lt;h2&gt;No mime type&lt;/h2&gt;
&lt;p&gt;You can leave out the mime type and have Rails use that template for all mimes, e.g. &lt;tt&gt;show.erb&lt;/tt&gt;. Both &lt;tt&gt;/people/1&lt;/tt&gt; and &lt;tt&gt;/people/1.js&lt;/tt&gt; will render that same template.&lt;/p&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/how_rails_selects_which_view_to_render</guid>
    </item>
    
    
    <item>
      <title>Creating Your Own Validations</title>
      <link>http://august.lilleaas.net/creating_your_own_validations</link>
      <description>&lt;p&gt;It is easy to create custom validations in Rails. Here&amp;#8217;s your full list of recipes.&lt;/p&gt;
&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base
  validate :any_method, :on =&amp;gt; :create
  
  validate do |record|
    record.errors.add_to_base("This sucks.") if record.does_it_suck?
  end
  
  def does_it_suck?
    false # do something real here.
  end
  
  private
  
  def any_method
    errors.add.to_base("I refuse to be saved!") if my_condition?
  end
end&lt;/pre&gt;
&lt;p&gt;You can also define a &lt;code&gt;validate&lt;/code&gt; method, but that is widely considered unelegant and oldschool. Use &lt;code&gt;validate :any_method&lt;/code&gt; or &lt;code&gt;validate {|record| ... }&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Validates each&lt;/h2&gt;
&lt;p&gt;You can use &lt;code&gt;validates_each&lt;/code&gt; to run the same validation on multiple attributes.&lt;/p&gt;
&lt;pre&gt;class User &amp;lt; ActiveRecord::Base
  validates_each(:home_email, :job_email) do |record, attribute, value|
    if value !~ /my fancy email regexp/
      record.errors.add(attribute, "My error message!")
    end
  end
end&lt;/pre&gt;
&lt;h2&gt;Custom validation methods&lt;/h2&gt;
&lt;p&gt;Deep down below, all the built-in validation methods also uses &lt;code&gt;validates_each&lt;/code&gt;. This makes it trivial to implement your own validation methods that you can use across your models.&lt;/p&gt;
&lt;pre&gt;# lib/validates_email.rb
class ActiveRecord::Base
  def self.validates_email(*args)
    validates_each(*args) do |record, attribute, value|
      if value !~ /my fancy email regexp/
        record.errors.add(attribute, "is not a valid e-mail address")
      end
    end
  end
end

# config/initializers/[anything].rb
require "validates_email"&lt;/pre&gt;
&lt;p&gt;This code passes on all the arguments as-is to &lt;code&gt;validates_each&lt;/code&gt;. This means that you can use all the various options that are common to the built-in validation methods, such as &lt;code&gt;:on =&amp;gt; :create&lt;/code&gt;, &lt;code&gt;:if =&amp;gt; :a_method&lt;/code&gt; and so on.&lt;/p&gt;
&lt;p&gt;Congratulations, you got yourself a professional looking custom validation!&lt;/p&gt;
&lt;pre&gt;class Contact &amp;lt; ActiveRecord::Base
  validates_email :home_email, :work_email, :on =&amp;gt; :create
end&lt;/pre&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/creating_your_own_validations</guid>
    </item>
    
    
    <item>
      <title>Load Path</title>
      <link>http://august.lilleaas.net/load_path</link>
      <description>&lt;p&gt;When you &lt;code&gt;require&lt;/code&gt; something, Ruby looks for a matching file in all the directories in the load path. The load path is stored in the global variable &lt;code&gt;$LOAD_PATH&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Consider the following directory structure:&lt;/p&gt;
&lt;pre&gt;
top_level.rb
underlings/
  slave.rb
  equal.rb
&lt;/pre&gt;
&lt;p&gt;You&amp;#8217;ll get an error if you try to &lt;code&gt;require "slave"&lt;/code&gt; from &lt;tt&gt;top_level.rb&lt;/tt&gt;. When you &lt;code&gt;require&lt;/code&gt; something, Ruby looks for a matching file in the directories of the &lt;code&gt;$LOAD_PATH&lt;/code&gt;. The directory &lt;tt&gt;underlings/&lt;/tt&gt; is not automatically added to the &lt;code&gt;$LOAD_PATH&lt;/code&gt; by Ruby, so the &lt;code&gt;require&lt;/code&gt; fails.&lt;/p&gt;
&lt;p&gt;If you on the other hand add &lt;tt&gt;underlings/&lt;/tt&gt; to the &lt;code&gt;$LOAD_PATH&lt;/code&gt;, it will work. Adding directories to the load path is easy.&lt;/p&gt;
&lt;pre&gt;# top_level.rb
$LOAD_PATH &amp;lt;&amp;lt; File.join(File.dirname(__FILE__), "underlings")
require "slave"&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;File.dirname(__FILE__)&lt;/code&gt; and &lt;code&gt;File.join&lt;/code&gt; is used to get the full absolute path to the &lt;tt&gt;underlings/&lt;/tt&gt; directory. You should only put absolute paths such as &lt;code&gt;"/usr/local/foo"&lt;/code&gt; (or &lt;code&gt;"C:\foo\bar"&lt;/code&gt; on Windows) in the &lt;code&gt;$LOAD_PATH&lt;/code&gt;, and avoid things like &lt;code&gt;$LOAD_PATH &amp;lt;&amp;lt; "lib/foo"&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The snippet above will run successfully, because the require statement is able to handle &lt;code&gt;"slave"&lt;/code&gt; based on what&amp;#8217;s in the &lt;code&gt;$LOAD_PATH&lt;/code&gt;. As you can see, &lt;code&gt;$LOAD_PATH&lt;/code&gt; is an array, and the directory names it contains are strings.&lt;/p&gt;
&lt;h2&gt;The current directory is in the load path&lt;/h2&gt;
&lt;p&gt;If you inspect &lt;code&gt;$LOAD_PATH&lt;/code&gt; in IRb, you&amp;#8217;ll find &lt;code&gt;"."&lt;/code&gt; in it. That dot reperesents the current directory, and lets you require a file that is in the same directory as the file you require from. If &lt;tt&gt;foo.rb&lt;/tt&gt; and &lt;tt&gt;bar.rb&lt;/tt&gt;, you can &lt;code&gt;require "bar"&lt;/code&gt; from &lt;tt&gt;foo.rb&lt;/tt&gt; without modifying the &lt;code&gt;$LOAD_PATH&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;That $: thing&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;$:&lt;/code&gt; is a shorthand for &lt;code&gt;$LOAD_PATH&lt;/code&gt;. So now you know.&lt;/p&gt;
&lt;p&gt;(In fact, &lt;code&gt;$LOAD_PATH&lt;/code&gt; is longhand for &lt;code&gt;$:&lt;/code&gt;. Yeah! Thanks, &lt;a href="http://smartic.us/"&gt;bryanl&lt;/a&gt;.)&lt;/p&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/load_path</guid>
    </item>
    
    
    <item>
      <title>Git Submodules</title>
      <link>http://august.lilleaas.net/git_submodules</link>
      <description>&lt;p&gt;Git uses submodules to store links to other repositories.&lt;/p&gt;
&lt;pre&gt;&amp;gt; git submodule add [repository] [local path]
&amp;gt; git submodule add git://github.com/foo/bar.git local/path&lt;/pre&gt;
&lt;p&gt;In this case, Git will clone the repository into &lt;tt&gt;local/path&lt;/tt&gt;. Git now stores a reference to the most recent commit in that repository in &lt;tt&gt;.gitmodules&lt;/tt&gt;. You have to add &lt;tt&gt;.gitmodules&lt;/tt&gt; and the submodule itself to the repository.&lt;/p&gt;
&lt;pre&gt;&amp;gt; git add .gitmodules
&amp;gt; git add local/path
&amp;gt; git commit -m "Adding my first submodule!"&lt;/pre&gt;
&lt;p&gt;This is what&amp;#8217;s in &lt;tt&gt;.gitmodules&lt;/tt&gt;:&lt;/p&gt;
&lt;pre&gt;[submodule "local/path"]
	path = local/path
	url = git://github.com/foo/bar.git
&lt;/pre&gt;
&lt;p&gt;&lt;tt&gt;git submodule&lt;/tt&gt; with no arguments will list all the submodules with their &lt;span class="caps"&gt;SHA&lt;/span&gt; refs.&lt;/p&gt;
&lt;pre&gt;&amp;gt; git submodule
 dc88847e5ce392eed210b97525c14fca55852867 local/path&lt;/pre&gt;
&lt;h2&gt;Using a specific commit or tag&lt;/h2&gt;
&lt;p&gt;In most cases you don&amp;#8217;t want to use the &lt;span class="caps"&gt;HEAD&lt;/span&gt; at the time you create the submodule, you want to use a particular commit or tag. You can &lt;tt&gt;cd&lt;/tt&gt; to the submodule and use &lt;tt&gt;git checkout&lt;/tt&gt; to specify which commit or tag you want to use for your submodule.&lt;/p&gt;
&lt;pre&gt;&amp;gt; cd local/path
&amp;gt; git checkout 58926a0077d9f3df66af3460eb8fe3bd0e68814d&lt;/pre&gt;
&lt;p&gt;In order to checkout a tag, you have to run &lt;tt&gt;git tag&lt;/tt&gt; first. Then, you can checkout to any tag you like.&lt;/p&gt;
&lt;pre&gt;&amp;gt; cd local/path
l/path &amp;gt; git tag
0.1
0.2
0.3b
0.3
l/path &amp;gt; git checkout 0.2&lt;/pre&gt;
&lt;p&gt;You can also use &lt;tt&gt;git pull&lt;/tt&gt; to get the most recent commit.&lt;/p&gt;
&lt;pre&gt;&amp;gt;cd local/path
l/path &amp;gt; git pull&lt;/pre&gt;
&lt;p&gt;You must then commit your changes.&lt;/p&gt;
&lt;pre&gt;l/path &amp;gt; cd ../..
&amp;gt; git add local/path
&amp;gt; git commit -m "Updating the submodule."&lt;/pre&gt;
&lt;h2&gt;Important: git add on a submodule.&lt;/h2&gt;
&lt;p&gt;When you use &lt;tt&gt;git add&lt;/tt&gt; on a submodule, make sure you don&amp;#8217;t have a tailing slash.&lt;/p&gt;
&lt;pre&gt;&amp;gt; git add local/path
  -- adds the submodule
  
&amp;gt; git add local/path/
  -- adds all the files in the submodule directly into your repository, big no-no&lt;/pre&gt;
&lt;h2&gt;Cloning a repository that uses submodules&lt;/h2&gt;
&lt;p&gt;When you clone a repository that utilizes submodules, you have to run two commands in order to fetch the submodules. Git doesn&amp;#8217;t do that automatically when you clone.&lt;/p&gt;
&lt;pre&gt;git submodule init
git submodule update&lt;/pre&gt;
&lt;h2&gt;Rails particulars&lt;/h2&gt;
&lt;p&gt;Since this site targets Railsers, I deem it sensible to have a Rails specific section. Here are a few useful commands:&lt;/p&gt;
&lt;pre&gt;&amp;gt; git submodule add git://github.com/rails/rails.git vendor/rails
&amp;gt; cd vendor/rails
v/rails &amp;gt; git tag
  ... a whole bunch of tags are listed...
v/rails &amp;gt; git checkout v2.1.2
v/rails &amp;gt; cd ../../
&amp;gt; git add .gitmodules
&amp;gt; git add vendor/rails
&amp;gt; git commit -m "Adding rails as a submodule"&lt;/pre&gt;

&lt;pre&gt;&amp;gt; git submodule add git://github.com/mislav/will_paginate.git vendor/plugins/will_paginate
&amp;gt; git add .
&amp;gt; git commit -m "Adding will_paginate as a submodule"&lt;/pre&gt;
&lt;h3&gt;Sources&lt;/h3&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;a href="http://daniel.collectiveidea.com/blog/2008/4/9/git-submodules"&gt;http://daniel.collectiveidea.com/blog/2008/4/9/git-submodules&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href="http://woss.name/2008/04/11/using-git-submodules-to-track-vendorrails-2/"&gt;http://woss.name/2008/04/11/using-git-submodules-to-track-vendorrails-2/&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;Terminal.app&lt;/li&gt;
&lt;/ul&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/git_submodules</guid>
    </item>
    
    
    <item>
      <title>Active Record Anywhere</title>
      <link>http://august.lilleaas.net/active_record_anywhere</link>
      <description>&lt;p&gt;You can use &lt;code&gt;ActiveRecord&lt;/code&gt; anywhere!&lt;/p&gt;
&lt;pre&gt;
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection({
  :adapter =&amp;gt; 'postgresql',
  :user =&amp;gt; 'foo',
  :password =&amp;gt; 'bar',
  :database =&amp;gt; 'whatever'
})

class Task &amp;lt; ActiveRecord::Base
  set_table_tame "a_legacy_thingie"
  
  def utility_methods
    update_attribute(:title, "yep")
  end
end

Task.find(:first)
&lt;/pre&gt;
&lt;p&gt;Etcetera. It&amp;#8217;s &lt;code&gt;ActiveRecord&lt;/code&gt;, you know what to do. Going wild:&lt;/p&gt;
&lt;pre&gt;
ActiveRecord::Base.establish_connection(:adapter =&amp;gt; "sqlite3", :dbfile =&amp;gt; ":memory:")

ActiveRecord::Schema.define(:version =&amp;gt; 1) do
  create_table :posts do |t|
    t.string :title
    t.text :excerpt, :body
  end
end

class Post &amp;lt; ActiveRecord::Base
  validates_presence_of :title
end

Post.create(:title =&amp;gt; "A new post!")
Post.create(:title =&amp;gt; "Another post", :excerpt =&amp;gt; "The excerpt is an excerpt.")

puts Post.count
# =&amp;gt; 2
&lt;/pre&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/active_record_anywhere</guid>
    </item>
    
    
    <item>
      <title>Procs And Blocks And Anonymous Functions</title>
      <link>http://august.lilleaas.net/procs_and_blocks_and_anonymous_functions</link>
      <description>&lt;p&gt;This is a Big Picture&amp;#8482; post. I will attempt to give you a thorough understanding of how blocks and procs works in Ruby by showing examples and explaining basics. I will also show some examples from other languages, namely Javascript and Lua, in order to really expand on the Big Picture&amp;#8482; in this article.&lt;/p&gt;
&lt;h2&gt;Storing pieces of code&lt;/h2&gt;
&lt;p&gt;In Ruby, you can store pieces of code and execute them on demand; methods. You define the method, add code to the method body, and run the method whenever you want.&lt;/p&gt;
&lt;p&gt;In addition to methods, there is another way in Ruby to store code that you can call later; procs.&lt;/p&gt;
&lt;pre&gt;say_hello = Proc.new { puts "Hello!" }&lt;/pre&gt;
&lt;p&gt;Contrary to what you might expect, the &lt;code&gt;puts&lt;/code&gt; doesn&amp;#8217;t run. Ruby only &lt;em&gt;stores&lt;/em&gt; the code inside the proc, it doesn&amp;#8217;t &lt;em&gt;run&lt;/em&gt; it. Not yet, at least. It runs when we tell it to. Let&amp;#8217;s run it right away. Remember, we stored the proc in the &lt;code&gt;say_hello&lt;/code&gt; variabe.&lt;/p&gt;
&lt;pre&gt;say_hello.call
# =&amp;gt; "Hello!"&lt;/pre&gt;
&lt;p&gt;So, there you go. That&amp;#8217;s what procs are, and that is all there is to it. But how the fsck is this useful to anyone? Why not just use methods?&lt;/p&gt;
&lt;h2&gt;Organizing your code with procs&lt;/h2&gt;
&lt;p&gt;Procs are useful code organization tools. Let&amp;#8217;s say that you want to calculate the running time for a few code snippets, in order to benchmark them. To do this elegantly, you want to be able to call a method and pass some code to it, and have the execution time returned.&lt;/p&gt;
&lt;p&gt;Here&amp;#8217;s how you can use procs to do just that:&lt;/p&gt;
&lt;pre&gt;def time(a_proc)
  start = Time.now
  a_proc.call
  puts Time.now - start
end

time(Proc.new { code_here })
time(Proc.new { more_code_here })&lt;/pre&gt;
&lt;p&gt;The execution times of the code inside the procs will be neatly displayed as you run this code. Try it yourself, right now! You can use &lt;code&gt;sleep(2)&lt;/code&gt;, &lt;code&gt;1000.times { 5 + 5 }&lt;/code&gt;, or anything else you might want to speed test.&lt;/p&gt;
&lt;h2&gt;Blocks!&lt;/h2&gt;
&lt;p&gt;In addition to method arguments, a method can also take a block. Passing a block is essentially the same as passing a proc, except that the syntax is different (and nicer), and you don&amp;#8217;t have to type as much. Other than that, procs and blocks are essential the same thing: code that you can call later on.&lt;/p&gt;
&lt;pre&gt;def time
  start = Time.now
  yield
  puts Time.now - start
end

time { code_here }
time { more_code_here }&lt;/pre&gt;
&lt;p&gt;Looks a lot nicer, doesn&amp;#8217;t it? Upon further inspection, it is easy to see where procs and blocks differs. Comparing the two examples, we can see that the &lt;code&gt;time&lt;/code&gt; method no longer takes an argument. A block is a special internal thing in Ruby, so you don&amp;#8217;t need to specify a method argument for the block. Also, we use &lt;code&gt;yield&lt;/code&gt; instead of &lt;code&gt;a_proc.call&lt;/code&gt;. &lt;code&gt;yield&lt;/code&gt; is a special keyword in Ruby, telling Ruby to call the code in the block that was passed to that method. Lastly, actually passing the code to the method has a different syntax. No parentheses, because the block is not an argument. No &lt;code&gt;Proc.new&lt;/code&gt; either, because we aren&amp;#8217;t creating a proc, we are passing a block.&lt;/p&gt;
&lt;h2&gt;Passing arguments to procs and blocks&lt;/h2&gt;
&lt;p&gt;When you &lt;code&gt;yield&lt;/code&gt; or &lt;code&gt;call&lt;/code&gt;, you can pass arguments to the proc or block at the same time. A dumb example:&lt;/p&gt;
&lt;pre&gt;def dumb_hello_world_test
  yield(5)
end

dumb_hello_world_test {|i| puts i * 2 }
# =&amp;gt; 10

my_silly_proc = Proc.new {|name| puts name.upcase }
my_silly_proc.call("August Lilleaas")
# =&amp;gt; "AUGUST LILLEAAS"&lt;/pre&gt;
&lt;p&gt;You have probably seen blocks taking arguments before: &lt;code&gt;each&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt; and other enumerable methods does this.&lt;/p&gt;
&lt;pre&gt;[1, 2, 3].map {|i| puts i * 2 }
# =&amp;gt; 2
# =&amp;gt; 4
# =&amp;gt; 6&lt;/pre&gt;
&lt;p&gt;That&amp;#8217;s right: map takes a block. The block gets an argument: the number in the array. Now, for something hardcore. Let&amp;#8217;s play with an implementation of &lt;code&gt;Array#each&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;class Array
  def each
    i = 0
    while(i &amp;lt; self.length) do
      yield(self[i])
      i += 1
    end
  end
end

my_array = ["a", "b", "c"]
my_array.each {|letter| puts letter }
# =&amp;gt; "a"
# =&amp;gt; "b"
# =&amp;gt; "c"&lt;/pre&gt;
&lt;p&gt;We iterate the items in the array, and call the block &amp;mdash; yield &amp;mdash; for every item in the array. When we yield, we pass the current array iteration to the block.&lt;/p&gt;
&lt;h2&gt;The big picture: blocks and procs in other languages.&lt;/h2&gt;
&lt;p&gt;Ruby isn&amp;#8217;t the only language that lets you pass around chunks of code. Here are some examples in Javascript and Lua. Despite their obvious use case differences, these two languages are pretty similar.&lt;/p&gt;
&lt;p&gt;Remember how you can use both methods and procs/blocks to store chunks of code in Ruby? In JS/Lua, methods and procs/blocks are replaced by functions. This is possible because, unlike Ruby, you can refer to a function by name without calling it, or create anonymous functions.&lt;/p&gt;
&lt;pre&gt;// javascript
var sayHello = function(){
  alert("Hello, World!");
}

sayHello    // a reference
sayHello()  // calling it

-- lua
local function sayHello()
  print("Hello, World!");
end

sayHello    -- a reference
sayHello()  -- calling it&lt;/pre&gt;
&lt;p&gt;Again, unlike Ruby, &lt;code&gt;sayHello&lt;/code&gt; won&amp;#8217;t execute the function, while &lt;code&gt;sayHello()&lt;/code&gt; will. Let&amp;#8217;s create an implementation of the &lt;code&gt;time&lt;/code&gt; method in JS and Lua.&lt;/p&gt;
&lt;pre&gt;// javascript
var time = function(callback){
  var start = new Date();
  callback();
  alert(new Date.getTime() - start.getTime());
}

time(function(){
  // run some code here..
});

-- lua
local function time(callback)
  local start = os.time();
  callback();
  print(os.time() - start);
end

time(function()
  -- run some code here..
end);&lt;/pre&gt;
&lt;p&gt;As you can see, you can pass an anonymous function definition directly to the two &lt;code&gt;time&lt;/code&gt; functions, as an argument &amp;mdash; similar to the way you Ruby lets you pass procs as method arguments.&lt;/p&gt;
&lt;p&gt;Just to elaborate, and as mentioned, you can pass a reference to a function as well as an actual function definition.&lt;/p&gt;
&lt;pre&gt;time(sayHello)&lt;/pre&gt;
&lt;p&gt;And just to make sure you&amp;#8217;re with me: &lt;code&gt;time(sayHello())&lt;/code&gt; will break miserably. &lt;code&gt;sayHello&lt;/code&gt; will execute before &lt;code&gt;time&lt;/code&gt;, which causes &lt;code&gt;time&lt;/code&gt; to use whatever executing &lt;code&gt;sayHello&lt;/code&gt; returns, instead of the function reference.&lt;/p&gt;
&lt;p&gt;Lastly, a Ruby recap. In Ruby, &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;foo()&lt;/code&gt; are equivalents.&lt;/p&gt;
&lt;pre&gt;def say_hello
  puts "Hello, World!"
end

say_hello
# =&amp;gt; "Hello, World!"
say_hello()
# =&amp;gt; "Hello, World!"&lt;/pre&gt;
&lt;p&gt;So, while other languages are able to pass around chunks of code by using references to other functions, Ruby doesn&amp;#8217;t allow that. Ruby has a separate feature for this, though; procs and blocks.&lt;/p&gt;
&lt;h2&gt;Relevant boring facts: Blocks to procs to blocks&lt;/h2&gt;
&lt;p&gt;You can convert a block passed to a method into a proc by using special syntax for this.&lt;/p&gt;
&lt;pre&gt;def time(&amp;amp;block)
  puts block
end

time
# =&amp;gt; nil
time { foo }
# =&amp;gt; #&amp;lt;Proc:0x00029bbc&amp;gt;&lt;/pre&gt;
&lt;p&gt;You can &lt;em&gt;also&lt;/em&gt; do this the other way around: pass a proc to a method and make it look as if you passed a block.&lt;/p&gt;
&lt;pre&gt;def time
  yield
end

my_proc = Proc.new { puts "I was called!" }
time(&amp;amp;my_proc)
# =&amp;gt; "I was called!"&lt;/pre&gt;
&lt;p&gt;The ampersand is the key here, which tells Ruby that &lt;code&gt;block&lt;/code&gt; and &lt;code&gt;my_proc&lt;/code&gt; isn&amp;#8217;t a method argument but a reference to the block passed to that method. Leave out the ampersand, and it&amp;#8217;ll be treated as a regular method argument.&lt;/p&gt;
&lt;pre&gt;def time(block)
  puts block
end

time { foo }
# =&amp;gt; ArgumentError: wrong number of arguments (0 for 1)
# Because the ampersand was left out in the method definition, the method now expects an
# argument, and it is given none (a block is not a method argument).

def time
  yield
end

time(my_proc)
# =&amp;gt; ArgumentError: wrong number of arguments (1 for 0)
# Because the time method doesn't take any arguments, and without the ampersand, my_proc 
# is passed as a regular method argument.&lt;/pre&gt;
&lt;h2&gt;Block syntax&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;do ... end&lt;/code&gt; and &lt;code&gt;{ ... }&lt;/code&gt; are equivalents. These two calls to &lt;code&gt;time&lt;/code&gt; are identical.&lt;/p&gt;
&lt;pre&gt;time { code_here }
  
time do
  code_here
end&lt;/pre&gt;
&lt;p&gt;The ideom is to use &lt;code&gt;do ... end&lt;/code&gt; on multi-line blocks, and &lt;code&gt;{ ... }&lt;/code&gt; for one-liner blocks. It is entirely up to you, though. Following the ideom is recommended, but Ruby doesn&amp;#8217;t enforce it.&lt;/p&gt;
&lt;h2&gt;A note on lambdas&lt;/h2&gt;
&lt;p&gt;Short answer: &lt;code&gt;lambda { foo }&lt;/code&gt; and &lt;code&gt;proc { foo }&lt;/code&gt; is essensially the same thing, you can use both interchangeable in your code.&lt;/p&gt;
&lt;p&gt;There is two differences, though: One is how it handles &lt;code&gt;return&lt;/code&gt;. I suggest reading &lt;a href="http://samdanielson.com/2007/3/19/proc-new-vs-lambda-in-ruby"&gt;this article&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The other is how it handles arguments. This is really lame and strange. &lt;code&gt;lambda&lt;/code&gt; and &lt;code&gt;proc&lt;/code&gt; are equivalents, while &lt;code&gt;Proc.new&lt;/code&gt; differs. You&amp;#8217;d think &lt;code&gt;Proc.new&lt;/code&gt; and &lt;code&gt;proc&lt;/code&gt; were equivalents, but they aren&amp;#8217;t. I&amp;#8217;ll let this code speak for itself.&lt;/p&gt;
&lt;pre&gt;a_lambda = lambda {|a| a.inspect }
puts a_lambda.call
# =&amp;gt; nil
puts a_lambda.call("foo", 5)
# =&amp;gt; ["foo", 5]

sumlam = lambda {|a, b| a + b }
sumlam.call
# =&amp;gt; ArgumentError: wrong number of arguments (0 for 2)

sumproc = proc {|a, b| a + b }
sumproc.call
# =&amp;gt; ArgumentError: wrong number of arguments (0 for 2)
sumproc.call(4, 5)
# =&amp;gt; 9

orlyproc = Proc.new {|a, b| a + b }
orlyproc.call
# =&amp;gt; NoMethodError: undefined method `+' for nil:NilClass
orlyproc.call(4, 5)
# =&amp;gt; 9&lt;/pre&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/procs_and_blocks_and_anonymous_functions</guid>
    </item>
    
    
    <item>
      <title>Where To Put Those Codes</title>
      <link>http://august.lilleaas.net/where_to_put_those_codes</link>
      <description>&lt;p&gt;You got &lt;tt&gt;app/&lt;/tt&gt; for your &lt;span class="caps"&gt;MVC&lt;/span&gt;, and &lt;tt&gt;vendor/&lt;/tt&gt; for your plugins, gems and what not. But what about everything else?&lt;/p&gt;
&lt;p&gt;There are two magic folders in a Rails app where that &amp;#8220;everything else&amp;#8221; goes:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;tt&gt;config/initializers/&lt;/tt&gt;&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;lib/&lt;/tt&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;They differ in behaviour. The code in &lt;tt&gt;config/initializers&lt;/tt&gt; runs when the application loads for the first time. The code in &lt;tt&gt;lib/&lt;/tt&gt; is only made available to your application, and doesn&amp;#8217;t execute until you explicitly call it.&lt;/p&gt;
&lt;p&gt;Confusion time. What&amp;#8217;s the difference between executing it on startup and making it available? The answer is &lt;code&gt;ActiveSupport::Dependencies&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;ActiveSupport::Dependencies&lt;/h2&gt;
&lt;p&gt;Normally, in order to make code available, Ruby has to execute the code. This is usually done with the &lt;code&gt;require&lt;/code&gt; keyword.&lt;/p&gt;
&lt;pre&gt;
# my_module.rb
module MyModule
  def my_method
    # a hardcore method that takes 10 seconds to run
  end
end

# my_file.rb
require "my_module"
&lt;/pre&gt;
&lt;p&gt;Ruby will execute the code in &lt;tt&gt;my_module.rb&lt;/tt&gt;. It will see the &lt;code&gt;module&lt;/code&gt; declaration and know that there now is a &lt;code&gt;MyModule&lt;/code&gt; module. It will see the method declaration (&lt;code&gt;def&lt;/code&gt;), and know that the module has a method called &lt;code&gt;my_method&lt;/code&gt;. It won&amp;#8217;t run the method &lt;code&gt;my_method&lt;/code&gt;, which is good. It will only run the file to the extent that it is aware of the method.&lt;/p&gt;
&lt;p&gt;The magic &lt;code&gt;ActiveSupport::Dependencies&lt;/code&gt; changes that, though. &lt;em&gt;You&lt;/em&gt; won&amp;#8217;t have to require files by hand to make the code in them available, it will require the files for you, automagically. &lt;code&gt;ActiveSupport::Dependencies.load_paths&lt;/code&gt; is an array of directory names. &lt;tt&gt;lib/&lt;/tt&gt; is in that list. Let&amp;#8217;s pretend that you have this file in &lt;tt&gt;lib/&lt;/tt&gt;:&lt;/p&gt;
&lt;pre&gt;
# lib/some_module.rb
module SomeModule
  def self.do_something
    # yeah, do something..
  end
end
&lt;/pre&gt;
&lt;p&gt;In a model, or in a controller, or anywhere, you call &lt;code&gt;SomeModule.do_something&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If this wasn&amp;#8217;t a Rails app, you would get an error message. You haven&amp;#8217;t explicitly required &lt;tt&gt;lib/some_module.rb&lt;/tt&gt;, which means that Ruby isn&amp;#8217;t aware of the &lt;code&gt;SomeModule&lt;/code&gt; module. It would raise &lt;code&gt;NameError&lt;/code&gt;, and fail miserably.&lt;/p&gt;
&lt;p&gt;Rails, however, captures this &lt;code&gt;NameError&lt;/code&gt;, and handles it with &lt;code&gt;ActiveSupport::Dependencies&lt;/code&gt;. It will look through all the directories in it&amp;#8217;s &lt;code&gt;load_paths&lt;/code&gt;. When it encounters the file &lt;tt&gt;some_module.rb&lt;/tt&gt; in either of those directories (the file name is based on the module name, &lt;tt&gt;SomeModule&lt;/tt&gt; turns into &lt;tt&gt;some_module&lt;/tt&gt;), it will require that file, and avoid the &lt;code&gt;NameError&lt;/code&gt; entirely.&lt;/p&gt;
&lt;p&gt;Back to my point: this means that the code in &lt;tt&gt;lib/&lt;/tt&gt; won&amp;#8217;t execute when you boot your app. You can &lt;code&gt;raise "OMG silly"&lt;/code&gt; in a file in &lt;tt&gt;lib/&lt;/tt&gt;, and your app will still boot. It will only execute when you call it.&lt;/p&gt;
&lt;p&gt;The code in &lt;tt&gt;config/initializers&lt;/tt&gt;, however, will execute when you boot the app. A &lt;code&gt;raise "dude.."&lt;/code&gt; in an initializer will make your app inbootable.&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;&lt;tt&gt;config/initializers/&lt;/tt&gt;&lt;/strong&gt; executes when the application boots. The name of the file does not matter, all the files in that directory will execute.&lt;/p&gt;
&lt;p&gt;It&amp;#8217;s good for plugin configuration such as &lt;span class="caps"&gt;API&lt;/span&gt; keys and various plugin settings, setting Rails configuration settings, adding inflections (for &lt;code&gt;pluralize&lt;/code&gt; and &lt;code&gt;singularize&lt;/code&gt;) and so on. It&amp;#8217;s basically a cleaner alternative to having code at the bottom of &lt;tt&gt;config/environment.rb&lt;/tt&gt;. Whenever old tutorials tells you to put something in &lt;tt&gt;environment.rb&lt;/tt&gt;, be smart, and put it in an initializer instead.&lt;/p&gt;
&lt;p&gt;Rails 2.1 and beyond comes with a set of default initializers. Look at them for some inspiration and examples.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;tt&gt;lib/&lt;/tt&gt;&lt;/strong&gt; stores code and makes it globally available to your app. It&amp;#8217;s great for extracting behaviour common to controllers and models, extracting common behaviour across multiple models or controllers into modules and so on.&lt;/p&gt;
&lt;p&gt;It&amp;#8217;s also good for code that aren&amp;#8217;t going to be re-used but perhaps only called in one of your models, but doesn&amp;#8217;t really belong in &lt;tt&gt;app/models&lt;/tt&gt; because it doesn&amp;#8217;t do anything with the database at all. If you write some code that fetches data from web services, for instance, tuck it in &lt;tt&gt;lib/&lt;/tt&gt; instead of making a none-&lt;code&gt;ActiveRecord::Base&lt;/code&gt;-class in &lt;tt&gt;app/models&lt;/tt&gt;.&lt;/p&gt;</description>
      <pubDate>Sun, 31 May 2009 16:32:20 GMT</pubDate>
      <guid>http://august.lilleaas.net/where_to_put_those_codes</guid>
    </item>
    
  </channel>
</rss>
