<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/atom10full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" xml:lang="en-gb"><title type="text">Barking Iguana</title>
<subtitle type="text">... and other strange tales ...</subtitle>

<link rel="alternate" type="text/html" href="http://barkingiguana.com/?source=feed" />
<id>tag:barkingiguana.com,2005:49231934267467cd6f9473e1d60d3904</id>
<generator uri="http://textpattern.com/" version="4.0.5">Textpattern</generator>
<updated>2008-11-20T10:50:43Z</updated>
<author>
		<name>Craig Webster</name>
		<email>craig@barkingiguana.com</email>
		<uri>http://barkingiguana.com/</uri>
</author>
<link rel="self" href="http://feeds.feedburner.com/BarkingIguana" type="application/atom+xml" /><entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-18T23:45:20Z</published>
		<updated>2008-11-19T11:22:30Z</updated>
		<title type="html">Symbol#to_proc is slow... is it slow enough to matter?</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/457767180/symbol-to_proc-is-slow-is-it-slow-enough-to-matter" />
		<id>tag:barkingiguana.com,2008-11-18:49231934267467cd6f9473e1d60d3904/1b423634cc67186d079a59a756b402f8</id>
		
		
		<summary type="html">
&lt;p&gt;It's common knowledge that using the to_proc hack is slower than not. Just how much slower is it? I decided to put together a few benchmarks to find out.&lt;/p&gt;


&lt;h4&gt;Environment&lt;/h4&gt;

&lt;p&gt;These tests were run on Ruby 1.8.6-pl111 and Rails 2.1.&lt;/p&gt;

&lt;h4&gt;Benchmarking&lt;/h4&gt;

&lt;p&gt;Say there's a database of 1,000 items that for some reason you want to iterate over. Let's forget that if you're showing 1,000 items you probably have usability issues and just roll with it.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;1_000.times { |n| Bar.create :name =&amp;gt; "bar-#{n}" }
bars = Bar.find(:all)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's how much slower it is over a dataset of 1,000 ActiveRecord instances.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;Benchmark.measure { bars.map(&amp;:name) }.real
#=&amp;gt; 0.00645709037780762

Benchmark.measure { bars.map { |b| b.name } }.real
#=&amp;gt; 0.00141692161560059&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that's a horrific increase: it takes more than 350% longer to run the to_proc hack than the plain block... but let's be realistic here, over 1,000 records it's taken 0.0065 seconds. Big woop. Who cares?&lt;/p&gt;

&lt;p&gt;How about over 1,000,000 rows? We already have 1,000 rows, let's top that up.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;(1_000_000 - 1_000).times { Bar.create :name =&amp;gt; Time.now.to_f.to_s }
bars = Bar.find(:all)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That makes it 1,000,000 rows in the table. By this stage your database is probably thinking you hate it. I'm pretty confident that presenting 1,000,000 rows to the person using your application is a bit of an edge case, but hey, here's how long it takes.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;Benchmark.measure { bars.map(&amp;:name) }.real
#=&amp;gt; 6.25304508209229

Benchmark.measure { bars.map { |b| b.name } }.real
#=&amp;gt; 1.38965106010437&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Almost 5 seconds extra over a million rows. Okay so 5 seconds is a pretty big hit, but how long will your application be running before you hit a million rows in one of your tables &lt;em&gt;and&lt;/em&gt; you need to iterate over all million rows?&lt;/p&gt;

&lt;p&gt;Don't optimise your code prematurely. By the time to_proc becomes an issue you'll already have hit many, many other problems.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;Benchmark.measure { Bar.find(:all) }.real
#=&amp;gt; 406.738657951355&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Worry about those first.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/457767180" height="1" width="1"/&gt;</summary>


<feedburner:origLink>http://barkingiguana.com/2008/11/18/symbol-to_proc-is-slow-is-it-slow-enough-to-matter?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-17T22:30:17Z</published>
		<updated>2008-11-17T21:10:47Z</updated>
		<title type="html">Handling error feedback from Ajax requests to Rails applications</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/456490305/handling-error-feedback-from-ajax-requests-to-rails-applications" />
		<id>tag:barkingiguana.com,2008-11-17:49231934267467cd6f9473e1d60d3904/8b096f7c1e082a76161d0c6c9e6ea0ab</id>
		<category term="Javascript" />
		<category term="Rails" />
		<summary type="html">
&lt;p&gt;Ajax is frequently used to provide a richer user experience. Why then are important error messages rarely handled properly in Ajax enabled applications? Handling errors gracefully and in a way that helps the visitor to solve them adds a really high quality feel to your application. We've got all the necessary machinery, all it takes is a little care and attention.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class FoosController &lt; ApplicationController
  def update
    @foo = Foo.find(params[:id])
    respond_to do |format|
      if @foo.save
        format.html do
          flash[:info] = "Your foo has been created."
          redirect_to @foo
        end
        format.js { head :ok }
      else
        format.html do
          flash.now[:warning] = "I could not update the foo."
          render :action =&gt; :edit
        end
        format.json do
          head :unprocessable_entity, :json =&gt; @foo.errors.to_json
        end
      end
    end
  end
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using the above code we get a lovely fallback HTML based behaviour and when we work with Ajax we get to use JSON behaviours. When JSON is requested and something goes wrong we get back an array of arrays that takes the following form.&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;[
  [ "attribute1", "error1", "error2" ],
  [ "attribute2", "error3"]
]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just think of the awesome things you could do with such rich feedback...&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;new Ajax.Request('/foo.json', {
  method: 'PUT',
  parameters: {
    authenticity_token: window._token,
    "foo[subject]": $F('foo_subject'),
    "foo[body]"   : $F('foo_body')
  },
  onSuccess: function(transport) {
    // This is Web 2.0: celebrate with a yellow highlight.
  },
  onFailure: function(transport) {
    var errors = transport.responseJSON;
    errors.each(function(error) {
      var attribute = error.shift();
      var messages = error.join(", ");
      var errorMessage = attribute + " " + messages;
      var inputNode = $("foo_" + attribute);
      if(inputNode) {
        // Show that something is wrong with this field.
        inputNode.addClassName("error");
        // Do something better than an alert box. Alert boxes suck.
        alert(errorMessage);
      }
    });
  }
});&lt;/code&gt;&lt;/pre&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/456490305" height="1" width="1"/&gt;</summary>

<category term="ajax" />
<category term="javascript" />
<category term="rails" />
<category term="snippets" />
<feedburner:origLink>http://barkingiguana.com/2008/11/17/handling-error-feedback-from-ajax-requests-to-rails-applications?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-17T20:21:36Z</published>
		<updated>2008-11-17T20:47:14Z</updated>
		<title type="html">Ajax and the Rails request authenticity token</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/456394708/ajax-and-the-rails-request-authenticity-token" />
		<id>tag:barkingiguana.com,2008-11-17:49231934267467cd6f9473e1d60d3904/4e6842153eff3dabf66053f2a590570f</id>
		<category term="Javascript" />
		<category term="Rails" />
		<summary type="html">
&lt;p&gt;Rails 1.2.6 introduced &lt;a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery"&gt;&lt;abbr title="Cross Site Request Forgery"&gt;CSRF&lt;/abbr&gt;&lt;/a&gt; protection in the form of an authenticity token which is a reasonably long string used to make sure that any PUT / POST / DELETE request you've made to an application was really generated by you (or at least your browser) doing something in the application and that you weren't tricked into submitting it by some nefarious third party.&lt;/p&gt;

&lt;p&gt;Rails automatically adds this token to any forms generated by it's helpers, but when building rich Ajax applications it can be useful to be able to generate the Javascript by hand.&lt;/p&gt;

&lt;p&gt;Fire this snippet into your layout just above including all the other Javascript files to get access to the authenticity token in Javascript and let you submit requests using Ajax.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%= javascript_tag "window._token = '#{form_authenticity_token}';" %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can build Ajax requests that are allowed to do stuff to the application.&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;new Ajax.Request('/foo.json', {
  method: 'PUT',
  parameters: {
    authenticity_token: window._token,
    text: $F('foo_text')
  }
  /* callbacks omitted for brevity */
})&lt;/code&gt;&lt;/pre&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/456394708" height="1" width="1"/&gt;</summary>

<category term="rails" />
<category term="javascript" />
<category term="ajax" />
<category term="snippets" />
<feedburner:origLink>http://barkingiguana.com/2008/11/17/ajax-and-the-rails-request-authenticity-token?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-16T14:35:47Z</published>
		<updated>2008-11-16T15:47:38Z</updated>
		<title type="html">Writing a Story: why, when, where, who, what, how and a bunch of other questions and answers</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/454943438/writing-a-story-why-when-where-who-what-how-and-a-bunch-of-other-questions-and-answers" />
		<id>tag:barkingiguana.com,2008-11-16:49231934267467cd6f9473e1d60d3904/5669f6789969939c6b50d9aa88cef69b</id>
		<category term="Stories" />
		<category term="Agile-Development" />
		<summary type="html">
&lt;p&gt;It's quite a head-shift to start using story-driven development. Often it's hard to work out what a story should contain and who should be involved in writing it. Wouldn't it be nice to have some guidelines to help you get started? &lt;a rel="bookmark" href="http://barkingiguana.com/2008/11/16/writing-a-story-why-when-where-who-what-how-and-a-bunch-of-other-questions-and-answers"&gt;Here are mine&lt;/a&gt;.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/454943438" height="1" width="1"/&gt;</summary>

<category term="stories" />
<category term="agile" />
<feedburner:origLink>http://barkingiguana.com/2008/11/16/writing-a-story-why-when-where-who-what-how-and-a-bunch-of-other-questions-and-answers?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-15T20:27:47Z</published>
		<updated>2008-11-15T21:24:41Z</updated>
		<title type="html">Get the current Git branch in your command prompt</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/454260068/get-the-current-git-branch-in-your-command-prompt" />
		<id>tag:barkingiguana.com,2008-11-15:49231934267467cd6f9473e1d60d3904/cc86b9fd190d0d45956ceb4808615532</id>
		<category term="Version-Control" />
		
		<summary type="html">
&lt;p&gt;It seems that everyone and their dog has their own way to represent the current Git branch in the command prompt. Here's mine. Stick it in your &lt;code&gt;~/.profile&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export PS1='\[\033[01;32m\]\u@\h\[\033[00m\] \[\033[01;34m\]\w\[\033[00m\]$(git branch &amp;&amp;gt;/dev/null; if [ $? -eq 0 ]; then echo "\[\033[01;33m\]($(git branch | grep ^*|sed s/\*\ //))\[\033[00m\]"; fi)$ '&lt;/code&gt;&lt;/pre&gt;

&lt;code&gt;&lt;span style="color: green;"&gt;craig@shiny&lt;/span&gt; &lt;span style="color: blue;"&gt;~/sandbox/addressbook&lt;/span&gt;&lt;span style="color: yellow;"&gt;(master)&lt;/span&gt;&lt;span style="color: green;"&gt;$&lt;/span&gt; &lt;/code&gt;

&lt;h4&gt;Now with 50% cleaner code&lt;/h4&gt;

&lt;p&gt;Not long after I posted this snippet I found a post about enabling &lt;a href="http://blog.ericgoodwin.com/2008/4/10/auto-completion-with-git"&gt;git auto-completion&lt;/a&gt;. If you use the auto-complete file that's bundled with Git you can use the following code to get the same prompt (and get some nifty tab-based goodies too).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export PS1='\[\033[01;32m\]\u@\h\[\033[00m\] \[\033[01;34m\]\w\[\033[00m\]$(__git_ps1 "\[\033[01;33m\](%s)\[\033[00m\]")$ '&lt;/code&gt;&lt;/pre&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/454260068" height="1" width="1"/&gt;</summary>

<category term="git" />
<category term="snippets" />
<feedburner:origLink>http://barkingiguana.com/2008/11/15/get-the-current-git-branch-in-your-command-prompt?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-15T19:34:21Z</published>
		<updated>2008-11-15T23:41:50Z</updated>
		<title type="html">Setting up a public Git repository</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/454229523/setting-up-a-public-git-repository" />
		<id>tag:barkingiguana.com,2008-11-15:49231934267467cd6f9473e1d60d3904/05152d6265369e8418c5af38d8eb9bc6</id>
		<category term="Version-Control" />
		
		<summary type="html">
&lt;p&gt;More and more these days I'm using Git as my version control system. I want to make code available to the general public. The easy choice would be to use a service like &lt;a href="http://github.com/"&gt;GitHub&lt;/a&gt; or &lt;a href="http://repo.or.cz/"&gt;repo.or.cz&lt;/a&gt; but I'm vain and want to serve my code from &lt;a href="http://barkingiguana.com/"&gt;barkingiguana.com&lt;/a&gt;. I don't need to support multiple committers and I'd like to learn more about how Git works so I don't want to use &lt;a href="http://eagain.net/gitweb/?p=gitosis.git;a=summary"&gt;Gitosis&lt;/a&gt;. It turns out that it's pretty easy to setup your own public repository...&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/454229523" height="1" width="1"/&gt;</summary>

<category term="git" />
<feedburner:origLink>http://barkingiguana.com/2008/11/15/setting-up-a-public-git-repository?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-11T12:07:31Z</published>
		<updated>2008-11-16T14:27:22Z</updated>
		<title type="html">Getting started with Story Driven Development for Rails with Cucumber</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/449471322/getting-started-with-story-driven-development-for-rails-with-cucumber" />
		<id>tag:barkingiguana.com,2008-11-11:49231934267467cd6f9473e1d60d3904/3199babca2ecfd813bc54a633bae5e80</id>
		<category term="Stories" />
		<category term="Agile-Development" />
		<summary type="html">
&lt;p&gt;I've been hearing about Story Driven Development (SDD) for a while but I haven't tried it out because I was under the impression that there was a huge amount to learn and setup before I could get going. I'm not sure if that used to be true, but I started using Cucumber yesterday and it was really easy.&lt;/p&gt;

&lt;h4&gt;Install and configure&lt;/h4&gt;

&lt;p&gt;You'll need to install a bunch of RubyGems.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo gem install nokogiri term-ansicolor treetop diff-lcs hpricot cucumber&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Install Cucumber into your Rails app.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ruby script/generate cucumber&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Install WebRAT. Unfortuantely this doesn't seem to be available as a RubyGem. If you're using Git then install this as a submodule instead. We're not so I clone the repository then &lt;code&gt;svn add&lt;/code&gt; it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone git://github.com/brynary/webrat.git vendor/plugin/webrat&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Writing your first story&lt;/h4&gt;

&lt;p&gt;Stories have three components: a business value, the role of a person that uses the feature and some description of the feature.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;In order to [do something with business value]
As [role]
Should [describe the feature]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An example might be the ability to order a pizza from the online ordering system of a pizza delivery company.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Feature: Order Pizza
  In order to get some hot, tasty pizza
  A hungry pizza lover
  Should be able to order pizza&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next we need to define some scenarios. Scenarios are things that can happen during the story. Most pizza places aren't open 24 hours a day so two simple scenarios are (1) the pizza shop is closed, and (2) the pizza shop is open.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  Scenario: The pizza shop is closed
    Given the pizza shop is closed
    And I am on the home page
    And I click "Feed Me!"
    Then I should see "Sorry, the shop is closed"

  Scenario: The pizza shop is open
    Given the pizza shop is open
    And I am on the home page
    And I click "Feed Me!"
    Then I should see "Your pizza will be with you soon"&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above description should go in a file called something like &lt;code&gt;features/order_pizza.feature&lt;/code&gt; where it is lovely and version controlled and safe.&lt;/p&gt;

&lt;p&gt;So, we now have a story that describes how a feature should behave. How does that get turned into acceptance tests? Well, you could pass these descriptions off to your testing team, or you could turn them into part of your test suite.&lt;/p&gt;

&lt;h4&gt;Automated tests: better than cake&lt;/h4&gt;

&lt;p&gt;You might notice that when installing Cucumber you got the directory &lt;code&gt;features/steps&lt;/code&gt;. That's where you tell your test suite how to understand your stories. There are already two files here: &lt;code&gt;common_webrat.rb&lt;/code&gt; which gives your test suite a few funky things like the ability to click links and &lt;code&gt;env.rb&lt;/code&gt; which does pretty much the same stuff as &lt;code&gt;spec/spec_helper.rb&lt;/code&gt; except for Cucumber. You can ignore &lt;code&gt;env.rb&lt;/code&gt;, but &lt;code&gt;common_webrat.rb&lt;/code&gt; will provide a few examples of how to start writing story steps.&lt;/p&gt;

&lt;p&gt;Create a new file, &lt;code&gt;order_pizza_steps.rb&lt;/code&gt;. This is where you define the steps involved in ordering pizza. It's pretty much just regular expressions which match each line of a scenario to some Ruby code.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;
Given /the pizza shop is open/ do
  PizzaShop.open = true
end

Given /the pizza shop is closed/ do
  PizzaShop.open = false
end

And /I am on the home page/ do
  visits "/"
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's all we need to do. The common WebRAT steps provide the necessary mapping for clicking buttons and checking for feedback.&lt;/p&gt;

&lt;h4&gt;Running your stories&lt;/h4&gt;

&lt;p&gt;This is pretty simple: run &lt;code&gt;rake features&lt;/code&gt;. You should get some rather pretty coloured output, and if anything has gone wrong Cucumber is pretty good at suggesting ways to fix it.&lt;/p&gt;

&lt;h4&gt;Found this article useful?&lt;/h4&gt;

&lt;p&gt;If you enjoyed this article I'd appreciate recommendations at &lt;a href="http://www.workingwithrails.com/recommendation/new/person/7241-craig-webster"&gt;Working with Rails&lt;/a&gt;.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/449471322" height="1" width="1"/&gt;</summary>

<category term="stories" />
<category term="testing" />
<category term="ruby" />
<category term="rails" />
<feedburner:origLink>http://barkingiguana.com/2008/11/11/getting-started-with-story-driven-development-for-rails-with-cucumber?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-06T17:06:29Z</published>
		<updated>2008-11-07T09:44:32Z</updated>
		<title type="html">Content_for is the new GOTO</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/444574579/content_for-is-the-new-goto" />
		<id>tag:barkingiguana.com,2008-11-06:49231934267467cd6f9473e1d60d3904/83ccc9551b3730c34b8b7ccbc34f43c7</id>
		
		
		<summary type="html">
&lt;p&gt;I don't like &lt;code class="ruby"&gt;content_for&lt;/code&gt;. Your view code jumps around up and down files and makes it hard to work out what's going on. It smells a lot like GOTO. When was the last time you saw someone recommend you use a GOTO?&lt;/p&gt;

&lt;h4&gt;content_for :javascript and content_for :css&lt;/h4&gt;

&lt;p&gt;Use of &lt;code class="ruby"&gt;content_for&lt;/code&gt; can be easily avoided, at least for including CSS and Javascript files. Include the controller name and action name in the body tag in your layout and properly qualify your CSS declarations.&lt;/p&gt;

&lt;pre&gt;&lt;code class="rails-html"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&amp;gt;
&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;&amp;lt;%= page_title %&amp;gt;&amp;lt;/title&amp;gt;
  &amp;lt;meta http-equiv="Content-Language" content="English" /&amp;gt;
  &amp;lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&amp;gt;
  &amp;lt;link rel="stylesheet" type="text/css" href="/stylesheets/simple.css" media="screen" /&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body id="&amp;lt;%= "#{controller.controller_name.tableize.singularize}_#{controller.action_name}" %&amp;gt; class="&amp;lt;%= "#{controller.controller_name.tableize.singularize} #{controller.action_name}" %&amp;gt;"&amp;gt;
  &amp;lt;%= yield %&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Say you were looking at the Posts views in your app, you can now style these using something like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class="css"&gt;.post.index .article .title { 
  font-size: 1.25em;
}

.post.show .article .title { 
  font-size: 0.9em;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or, in case you need to support browsers that don't let you specify two classes as a selector for a single element, you can write it like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class="css"&gt;#post_index .article .title { 
  font-size: 1.25em;
}

#post_show .article .title { 
  font-size: 0.9em;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since all your Javascript is unobtrusive anyway (right?), it should be pretty easy to qualify the selectors used there with the same CSS selectors shown above.&lt;/p&gt;

&lt;p&gt;As an added bonus, by specifying your Javascript / CSS like the above you can package it all in one Javascript or CSS file on deployment to your production environment and save yourself a bunch of HTTP requests.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/444574579" height="1" width="1"/&gt;</summary>

<category term="css" />
<category term="snippets" />
<category term="rails" />
<feedburner:origLink>http://barkingiguana.com/2008/11/06/content_for-is-the-new-goto?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-11-03T22:56:15Z</published>
		<updated>2008-11-03T22:57:49Z</updated>
		<title type="html">Make sure you're @importing files that exist</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/441470657/make-sure-youre-importing-files-that-exist" />
		<id>tag:barkingiguana.com,2008-11-03:49231934267467cd6f9473e1d60d3904/badce7297a40569dbd859e997e2304ef</id>
		
		
		<summary type="html">
&lt;p&gt;A few people near me have heard the start of my rumblings about optimising the number of HTTP requests required for each page. There are a variety of reasons that you might want to do this, but that discussion is for another post. For now simply assume that I don't like unnecessary HTTP requests. Extrapolating from that you would reasonably assume that I &lt;em&gt;really&lt;/em&gt; don't like wasted HTTP requests such as might happen when the url in a CSS &lt;code class="css"&gt;@import&lt;/code&gt; directive 404's. If you assumed that, you'd be right.&lt;/p&gt;

&lt;p&gt;I got fed up of tracking down the source of these errors in a few applications that I maintain so I fired up a &lt;a href="http://macromates.com/"&gt;TextMate&lt;/a&gt; session and scraped together this nasty little snippet of Ruby to do my dirty work for me.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;#! /usr/bin/env ruby

css_root = File.expand_path(`pwd`.strip)
css_files = Dir[File.join(css_root, "**", "*.css")]

missing_imports = Hash.new([])
css_files.each_with_index do |css_file, index|
  imports = File.read(css_file).split(/\n|\r/).grep(/\@import url\((.*)\)/)
  imports.each do |import|
    desired_path = import.scan(/url\((["'\ ])?(.*)\1\)/).to_a.first.to_a.last
    desired_root = desired_path[0,1] == "/" ? css_root : File.dirname(css_file)
    filesystem_path = File.expand_path(File.join(desired_root, desired_path))
    if !File.exists?(filesystem_path)
      missing_imports[css_file] += [{ :path =&gt; filesystem_path, :directive =&gt; import }]
    end
  end
end

if missing_imports.any?
  puts "Missing files declared as imports in CSS:\n\n"

  missing_imports.keys.each do |origin|
    puts "Origin:               #{origin}"
    missing_imports[origin].each do |import|
      puts "Missing @import file: #{import[:path]}"
      puts "Directive:            #{import[:directive]}"
    end
    puts ""
  end
else
  puts "No imported files are missing. Well done."
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run it in the directory which serves your document root - for Rails applications this would be &lt;code&gt;RAILS_ROOT/public/&lt;/code&gt; - and it'll either spit out a list of missing files you've tried to &lt;code class="css"&gt;@import&lt;/code&gt; or tell you that you've done well.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Missing files declared as imports in CSS:

Origin:               /Users/craig/projects/1.8/public/stylesheets/.../find_by_service.css
Missing @import file: /Users/craig/projects/1.8/public/stylesheets/.../a_to_z.css
Directive:            @import url('.../a_to_z.css');&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, just to be clear, I don't like &lt;code class="css"&gt;@import&lt;/code&gt; directives. I'd prefer they were completely removed from the CSS. They are popular with a lot of people though so I'll compromise for the moment: if you must use them, please make sure they're going to work.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/441470657" height="1" width="1"/&gt;</summary>

<category term="css" />
<category term="ruby" />
<category term="snippets" />
<category term="debugging" />
<feedburner:origLink>http://barkingiguana.com/2008/11/03/make-sure-youre-importing-files-that-exist?source=feed</feedburner:origLink></entry>
<entry>
		<author>
			<name>Craig Webster</name>
		</author>
		<published>2008-10-31T23:39:57Z</published>
		<updated>2008-10-31T23:42:56Z</updated>
		<title type="html">Scaling: Using MogileFS for storing uploaded images</title>
		<link rel="alternate" type="text/html" href="http://feeds.feedburner.com/~r/BarkingIguana/~3/438551008/scaling-using-mogilefs-for-storing-uploaded-images" />
		<id>tag:barkingiguana.com,2008-10-31:49231934267467cd6f9473e1d60d3904/48b993ec8152a4fedbc6be8a2e0d295f</id>
		<category term="Scaling" />
		<category term="Rails" />
		<summary type="html">
&lt;p&gt;As you might have guessed from several of my previous posts, The team I've been working in has recently been scaling an application. I've learned a bunch of things along the way, several of which I've got half-written articles about and which I'll totally finish one day, honest.&lt;/p&gt;

&lt;p&gt;One of the most awesome technologies I've started using is &lt;a href="http://www.danga.com/mogilefs/"&gt;MogileFS&lt;/a&gt;, a distributed &lt;acronym title="Big load of binary"&gt;BLOB&lt;/acronym&gt; store. In out application we use this to store user-generated assets such as uploaded images and syndication feeds. I'll not go into the pros and cons of the technology here (I might do that another time), rather I'd like to share some code that we've found rather useful when handling image uploads and adding them to MogileFS: the &lt;code class="ruby"&gt;MogileFilesystemBackend&lt;/code&gt; for &lt;a href="http://github.com/technoweenie/attachment_fu/tree/master"&gt;AttachmentFu&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It's necessary to use a shared filestore for uploaded images when the application cluster you're using for uploads needs to scale beyond one physical box as otherwise the uploaded images land on several disks and there's no telling if they'll be available to a particular request to your application (that depends on which application server serves the request).&lt;/p&gt;

&lt;h4&gt;Getting stuck in&lt;/h4&gt;

&lt;p&gt;I've done some rather ugly preparation for this work and monkey-patched &lt;code class="ruby"&gt;Kernel&lt;/code&gt; to provide an &lt;code class="ruby"&gt;attr_accessor&lt;/code&gt; called &lt;code class="ruby"&gt;filestore&lt;/code&gt; which is just an instance of &lt;a href="http://barkingiguana.com/"&gt;MogileFS::MogileFS&lt;/a&gt; from the rather excellent &lt;a href="http://seattlerb.rubyforge.org/mogilefs-client/"&gt;MogileFS client&lt;/a&gt; by the clever people over at &lt;a href="http://seattlerb.rubyforge.org/"&gt;Seattle RB&lt;/a&gt;. The patch, which I'm sure will make experienced Rubyists cry, looks like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;module Kernel
  # Oh noes, I'm screwing with Kernel.
  # 
  mattr_accessor :filestore
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;During the Rails initializer execution the filestore is setup using configuration values pulled from a YAML file in &lt;code&gt;RAILS_ROOT/config/&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;Kernel.filestore = MogileFS::MogileFS.new(
  :domain =&gt; "APPNAME-#{RAILS_ENV}",
  :hosts =&gt; array_of_hosts_from_yaml_file
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(What I actually do is quite a bit different from this but that's because I've done evil things to the MogileFS client library which I'll probably share in the future. For now, believe the magic).&lt;/p&gt;

&lt;p&gt;Now that the setup is complete, how do we get AttachmentFu to work with the filestore? We use the &lt;code class="ruby"&gt;MogileFilesystemBackend&lt;/code&gt; of course!&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class Image &lt;&lt; ActiveRecord::Base
  has_attachment :content_type =&gt; :image,
    :storage =&gt; :mogile_filesystem,
    :max_size =&gt; 5.megabytes,
    :thumbnails =&gt; {
      :canonical =&gt; '1024x'
    },
    :processor =&gt; "MiniMagick"

  validates_as_attachment
end&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;The power behind the man&lt;/h4&gt;

&lt;p&gt;Of course, without the actual backend code not much is going to happen. The implementation was pretty heavily influenced by the existing Amazon S3 backend, mostly because the idea behind S3 and MogileFS is very similar.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;module MogileFilesystemBackend
  def full_filename(thumbnail = nil)
    "#{class_prefix}:#{filestore_tag(thumbnail)}"
  end

  def filestore_tag(thumbnail = nil)
    "#{parent_id || id}:#{thumbnail || :original}"
  end

  def current_content
    temp_path ? File.read(temp_path) : temp_data
  end
  
  def public_filename(thumbnail = nil)
    [
      editorial_object_type.demodularize.tableize,
      editorial_object_id,
      "#{class_prefix}.#{file_extension}#{thumbnail &amp;&amp; "?size=#{thumbnail}"}"
    ].join("/")
  end

  def file_extension
    Mime::Type.lookup(content_type).to_sym
  end

  def filestore_paths(thumbnail = nil)
    filestore.get_paths(full_filename(thumbnail))
  end

  def file_data(thumbnail = nil)
    filestore.get_file_data(full_filename(thumbnail))
  end

  protected
  def current_content_location
    temp_path ? :temp_path : :temp_data
  end

  def destroy_file
    filestore.delete full_filename
  end

  def rename_file
    filestore.rename @old_filename, full_filename
  end

  def save_to_storage
    logger.info "Storing #{self.class.name}\##{id} as #{full_filename(thumbnail)} (class: #{replication_policy}) from #{current_content_location == :temp_path ? temp_path : :memory}"
    filestore.store_content full_filename(thumbnail), replication_policy, current_content
  end

  def class_prefix
    self.class.name.demodularize.underscore.downcase
  end
  alias :replication_policy, :class_prefix
end

Technoweenie::AttachmentFu::Backends::MogileFilesystemBackend = ::MogileFilesystemBackend&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Serving the public&lt;/h4&gt;

&lt;p&gt;So now you can get images into MogileFS, but in order to be useful we also need to serve them to the visitors of our application. That'll require a little work in the controller to make it read from the ever-present &lt;code class="ruby"&gt;filestore&lt;/code&gt; instead of the database (if you're storing files in the database I will HURT you) or the local filesystem.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class ImageController &lt; ApplicationController
  before_filter :load_image

  def show
  respond_to do |format|
    format.html
    format.any(:png, :jpg, :gif) do
      send_data @image.file_data(params[:size]),
        :type =&gt; @image.content_type,
        :disposition =&gt; 'inline'
    end
  end
  
  protected
  def load_image
    @image = Image.find(params[:id])
  end
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There we have it. Images can now be requested through the ImageController and served to your adoring fans.&lt;/p&gt;

&lt;h4&gt;Found this article useful?&lt;/h4&gt;

&lt;p&gt;If you enjoyed this article I'd appreciate recommendations at &lt;a href="http://www.workingwithrails.com/recommendation/new/person/7241-craig-webster"&gt;Working with Rails&lt;/a&gt;.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/BarkingIguana/~4/438551008" height="1" width="1"/&gt;</summary>

<category term="scaling" />
<category term="system" />
<category term="mogilefs" />
<category term="rails" />
<feedburner:origLink>http://barkingiguana.com/2008/10/31/scaling-using-mogilefs-for-storing-uploaded-images?source=feed</feedburner:origLink></entry></feed>
