<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Adventures with Ruby</title>
    <description>Article feed of Adventures with Ruby</description>
    <link>http://iain.nl</link>
    <pubDate>Mon, 21 May 2012 07:00:00 GMT</pubDate>
    <item>
      <title>Sass 3.2 blocks</title>
      <link>http://iain.nl/sass-3-2-blocks</link>
      <pubDate>Mon, 21 May 2012 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>A lot of websites have side bars. On normal desktop browsers, this fits nicely. But
on smaller screens, it will create horizontal scrollbars. And those are a bad
user experience. Luckily, CSS supports <code>@media</code> directives that act on
different sizes.</p>

<p>Sass 3.2 is going to ship with an awesome new feature: blocks.  Just like Ruby.
Instead of <code>yield</code>, you use <code>@content</code>. The rest is exactly the same. You can
place anything inside your blocks: selectors (like <code>table.products</code>) and rules
(like <code>border: 1px solid gold</code>).</p>

<p>The <a href="https://github.com/nex3/sass/blob/master/doc-src/SASS_REFERENCE.md#passing-content-blocks-to-a-mixin-mixin-content">Sass
documentation</a>
mentions that you can use it to specify it for IE6 compatibility, but I like it
most for making my design responsive. Just create a mixin that places the
<code>@content</code> inside the <code>@media</code> directive.</p>

<p>The following scss code defines mixins for small screens and big screens. You
could even go further and define 3 categories, really small screens for mobile
phones, medium sized screens like tablets and small desktop windows, and your
normal big layout.</p>
<pre><span class="Identifier">$site-width</span>: <span class="Number">1000px</span>;

<span class="PreProc">@mixin</span> small-screen <span class="Function">{</span>
  <span class="Special">@media</span> only screen and (max-width: <span class="Identifier">$site-width</span> <span class="Special">+</span> 99px) <span class="Function">{</span>
    @content;
  <span class="Function">}</span>
<span class="Function">}</span>

<span class="PreProc">@mixin</span> big-screen <span class="Function">{</span>
  <span class="Special">@media</span> only screen and (min-width: <span class="Identifier">$site-width</span> <span class="Special">+</span> 100px) <span class="Function">{</span>
    @content;
  <span class="Function">}</span>
<span class="Function">}</span></pre>
<p>I add around 100px, which makes the switch between big and small screen styling
happen a bit earlier. This makes it always have a bit of margin, which I like.</p>

<p>For smaller screens, it is common to make the site fill the width of the window
and place columns underneath each other. The following code does that.</p>
<pre><span class="Identifier">$grid-count</span>: <span class="Number">12</span>;

<span class="Special">.</span><span class="Type">container</span> <span class="Function">{</span>
  <span class="PreProc">@include</span> big-screen <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Identifier">$site-width</span>;
    <span class="Type">margin</span>: <span class="Number">0</span> <span class="Type">auto</span>;
  <span class="Function">}</span>
  <span class="PreProc">@include</span> small-screen <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Type">auto</span>
  <span class="Function">}</span>
<span class="Function">}</span>
<span class="Special">.</span><span class="Type">column</span> <span class="Function">{</span>
  <span class="PreProc">@include</span> big-screen <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Identifier">$site-width</span> / <span class="Identifier">$grid-count</span>;
    <span class="Type">float</span>: <span class="Type">left</span>;
  <span class="Function">}</span>
  <span class="PreProc">@include</span> small-screen <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Type">auto</span>;
    <span class="Type">float</span>: <span class="Type">none</span>;
  <span class="Function">}</span>
<span class="Function">}</span></pre>
<p>I have found that it with this approach, it is easiest to split the CSS into
layout and styling. The styling, like colors and font-size, is probably the
same on every screen, but the size, padding and floating of elements will
change depending on the screen size.</p>

<p>In this case, I&#39;d like place the <code>@media</code> directive around the tags, creating a
clear distinction between layout for big and small screens:</p>
<pre><span class="Identifier">$grid-count</span>: <span class="Number">12</span>;

<span class="PreProc">@include</span> big-screen <span class="Function">{</span>
  <span class="Special">.</span><span class="Type">container</span> <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Identifier">$site-width</span>;
    <span class="Type">margin</span>: <span class="Number">0</span> <span class="Type">auto</span>;
  <span class="Function">}</span>
  <span class="Special">.</span><span class="Type">column</span> <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Identifier">$site-width</span> / <span class="Identifier">$grid-count</span>;
    <span class="Type">float</span>: <span class="Type">left</span>;
  <span class="Function">}</span>
<span class="Function">}</span>

<span class="PreProc">@include</span> small-screen <span class="Function">{</span>
  <span class="Special">.</span><span class="Type">container</span> <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Type">auto</span>;
  <span class="Function">}</span>
  <span class="Special">.</span><span class="Type">column</span> <span class="Function">{</span>
    <span class="Type">width</span>: <span class="Type">auto</span>;
    <span class="Type">float</span>: <span class="Type">none</span>;
  <span class="Function">}</span>
<span class="Function">}</span></pre>
<p>It depends on your site, which approach works best for you. It will result in
the same CSS. The <code>@media</code> directive is not allowed nested. <a href="https://github.com/nex3/sass/blob/master/doc-src/SASS_REFERENCE.md#media-media">Sass will
automatically correct
it</a>
if for you anyway. You got to love Sass for things like this!</p>

<p>I&#39;ve seen some projects with really complicated mixins, taking in really
complicated arguments. This will definitely clean this up.</p>
]]>
      </description>
      <guid>http://iain.nl/sass-3-2-blocks</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Testing ActiveRecord in isolation</title>
      <link>http://iain.nl/testing-activerecord-in-isolation</link>
      <pubDate>Thu, 22 Mar 2012 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Testing ActiveRecord doesn&#39;t have to be slow. With some clever loading you can
require only the parts that you need and it isn&#39;t even that difficult.</p>

<p>Another reason might be that you&#39;re using ActiveRecord without Rails. This
might be in another framework like Sinatra, or in a gem. Without Rails you
might be lost a little on how to set up ActiveRecord.</p>

<h2 id="toc_0">Preparation</h2>

<p>First, install the gems you&#39;ll need. This should be enough:</p>
<pre>gem install activerecord rspec sqlite3
</pre>
<p>I&#39;m using a really simple spec to get up and running. I&#39;m even defining the
model inside the spec itself, just because it&#39;s easier to get started:</p>
<pre><span class="Comment"># spec/widget_spec.rb</span>

<span class="rubyControl">class</span> <span class="Type">Widget</span> &lt; <span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Base</span>
  validates_presence_of <span class="Constant">:name</span>
<span class="rubyControl">end</span>

describe <span class="Type">Widget</span> <span class="rubyControl">do</span>

  it <span class="rubyStringDelimiter">"</span><span class="String">requires a name</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
    subject.name = <span class="rubyStringDelimiter">""</span>
    subject.should have(<span class="Number">1</span>).error_on(<span class="Constant">:name</span>)
    subject.name = <span class="rubyStringDelimiter">"</span><span class="String">Foo</span><span class="rubyStringDelimiter">"</span>
    subject.should have(<span class="Constant">:no</span>).errors_on(<span class="Constant">:name</span>)
  <span class="rubyControl">end</span>

<span class="rubyControl">end</span></pre>
<h2 id="toc_1">Loading ActiveRecord</h2>

<p>Run this spec on its own, simply by running:</p>
<pre>rspec spec/widget_spec.rb
</pre>
<p>You&#39;ll see that it doesn&#39;t even know ActiveRecord yet.</p>

<p>Let&#39;s create a support file for specs that need ActiveRecord. I put this in
<code>spec/support/active_record.rb</code>.</p>

<p>For now, this file will just require ActiveRecord for us:</p>
<pre><span class="Comment"># Create the file spec/support/active_record.rb:</span>

<span class="PreProc">require</span> <span class="rubyStringDelimiter">'</span><span class="String">active_record</span><span class="rubyStringDelimiter">'</span></pre>
<p>We need ActiveRecord before we define our model, so require the support file at
the very top of your spec:</p>
<pre><span class="Comment"># Prepend to spec/widget_spec.rb:</span>

<span class="PreProc">require</span> <span class="rubyStringDelimiter">'</span><span class="String">support/active_record</span><span class="rubyStringDelimiter">'</span></pre>
<p>RSpec automatically adds the <code>lib</code> and <code>spec</code> directory to the load paths, so
these files can be required easily.</p>

<h2 id="toc_2">Connecting with the database</h2>

<p>When we run the spec now, it should tell us that ActiveRecord has no connection
with the database. I&#39;m going for a SQLite database in memory, so let&#39;s define
the connection in the support file.</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Base</span>.establish_connection <span class="Constant">adapter</span>: <span class="rubyStringDelimiter">"</span><span class="String">sqlite3</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">database</span>: <span class="rubyStringDelimiter">"</span><span class="String">:memory:</span><span class="rubyStringDelimiter">"</span></pre>
<p>When we run it now, it will tell us that we don&#39;t have a table yet.</p>

<h2 id="toc_3">Run migrations</h2>

<p>If you have migrations, you can run them with just one simple line:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Migrator</span>.up <span class="rubyStringDelimiter">"</span><span class="String">db/migrate</span><span class="rubyStringDelimiter">"</span></pre>
<p>You can also just create the migration inline, which is probably even simpler:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Migration</span>.create_table <span class="Constant">:widgets</span> <span class="rubyControl">do</span> |<span class="Identifier">t</span>|
  t.string <span class="Constant">:name</span>
  t.timestamps
<span class="rubyControl">end</span></pre>
<p>If you have a <code>schema.rb</code> file, you can simply load it:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="PreProc">load</span> <span class="rubyStringDelimiter">"</span><span class="String">path/to/db/schema.rb</span><span class="rubyStringDelimiter">"</span></pre>
<h2 id="toc_4">Getting some RSpec helpers</h2>

<p>When we run it now, we&#39;ll see the familiar output of the migrations. The next
error we get is an undefined method <code>error_on</code>.</p>

<p>If your project already depends on <code>rspec-rails</code>, you can simply require the file:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>
<span class="PreProc">require</span> <span class="rubyStringDelimiter">'</span><span class="String">rspec/rails/extensions/active_record/base</span><span class="rubyStringDelimiter">'</span></pre>
<p>If you&#39;re not in a Rails project (but in a Gem or Engine), you might not want
to have rspec-rails as a dependency, because it adds a lot of extra
dependencies. You can just define the <code>error_on</code> method yourself, by
copy-pasting it:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="rubyControl">module</span> <span class="Type">ActiveModel</span><span class="Operator">::</span><span class="Type">Validations</span>
  <span class="Comment"># Extension to enhance `should have` on AR Model instances.  Calls</span>
  <span class="Comment"># model.valid? in order to prepare the object's errors object.</span>
  <span class="Comment">#</span>
  <span class="Comment"># You can also use this to specify the content of the error messages.</span>
  <span class="Comment">#</span>
  <span class="Comment"># @example</span>
  <span class="Comment">#</span>
  <span class="Comment">#     model.should have(:no).errors_on(:attribute)</span>
  <span class="Comment">#     model.should have(1).error_on(:attribute)</span>
  <span class="Comment">#     model.should have(n).errors_on(:attribute)</span>
  <span class="Comment">#</span>
  <span class="Comment">#     model.errors_on(:attribute).should include("can't be blank")</span>
  <span class="rubyControl">def</span> <span class="Function">errors_on</span>(attribute)
    <span class="Constant">self</span>.valid?
    [<span class="Constant">self</span>.errors<span class="Operator">[</span>attribute<span class="Operator">]</span>].flatten.compact
  <span class="rubyControl">end</span>
  <span class="Keyword">alias</span> <span class="Constant">:error_on</span> <span class="Constant">:errors_on</span>
<span class="rubyControl">end</span></pre>
<p>This should be enough to get your spec running! And look how fast it is!
Clearly, loading ActiveRecord isn&#39;t what makes Rails startup time slow.</p>

<h2 id="toc_5">Transactions</h2>

<p>The last part you&#39;ll want is to run your specs in transactions, so that one
spec doesn&#39;t influence the others. To do this, we&#39;ll make a simple around
filter:</p>
<pre><span class="Comment"># Append to spec/support/active_record.rb:</span>

<span class="Type">RSpec</span>.configure <span class="rubyControl">do</span> |<span class="Identifier">config</span>|
  config.around <span class="rubyControl">do</span> |<span class="Identifier">example</span>|
    <span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Base</span>.transaction <span class="rubyControl">do</span>
      example.run
      <span class="Statement">raise</span> <span class="Type">ActiveRecord</span><span class="Operator">::</span><span class="Type">Rollback</span>
    <span class="rubyControl">end</span>
  <span class="rubyControl">end</span>
<span class="rubyControl">end</span></pre>
<p>The <code>ActiveRecord::Rollback</code> exception will be caught by the transaction block
and roll back all the database changes after each spec.</p>

<h2 id="toc_6">Profit!!!</h2>

<p>Now, you might want to clean it up a little more, but this should be enough to
getting you started testing your ActiveRecord classes in (relative) isolation.
And the cool thing is, running these specs hardly takes any time!</p>

<p>If you have any tips, please share them in the comment-section below.</p>

<p>If you want to know more about how ActiveRecord works, I can recommended <a href="http://www.tamingthemindmonkey.com/">this
good series of posts</a> by <a href="http://twitter.com/robinroest">Robin
Roestenburg</a>. In the course of several blog
posts he dives into the inner workings of ActiveRecord, even refactoring parts
of it.</p>

<p>Next up: Testing controllers in isolation. Stay tuned!</p>
]]>
      </description>
      <guid>http://iain.nl/testing-activerecord-in-isolation</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Getting the Most out of Bundler Groups</title>
      <link>http://iain.nl/getting-the-most-out-of-bundler-groups</link>
      <pubDate>Sat, 10 Mar 2012 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Did you know you can create as many groups in Bundler as you like? You can and
I think you should! Let me show you some ways I use groups to clean up my
Gemfile.</p>

<h2 id="toc_0">Why groups?</h2>

<p><strong>Speed:</strong> Requiring gems can get slow, even more so when you have a lot of
them. Groups help you require the gems only when they are needed.</p>

<p>This is especially true if you use Ruby 1.9.2. In this version of Ruby, the
<code>require</code> statement can get very slow. The number of gems inside a
project can get rather large, so loading only the gems that are needed can improve
Rails&#39; boot time immensely.</p>

<p><strong>Safety:</strong> Some gems provide functionality that you don&#39;t want to enable in
certain cases.  Take webmock, for instance. This handy gem blocks all outgoing
network traffic inside your application. Very handy for testing purposes, but
not in production!</p>

<p><strong>Clarity:</strong> The group name can act as documentation. If you ever wonder what
a gem does and where it is used inside your application, a group can tell you a
lot.</p>

<h2 id="toc_1">The Basics</h2>

<p>You probably already know the basics of groups in Bundler. Rails already uses
groups out of the box. If you have a group named after the Rails environment,
it will get loaded.</p>

<p>If you have gems that are used in the application itself, your best bet is to
put them outside of any group. I&#39;m talking about gems like Rails itself,
devise, will_paginate, and so on.</p>

<p>Gems without a specified group are placed in the <code>:default</code> group and will be
loaded in every Rails environment.</p>

<p>This is your safest choice. When in doubt in which group to place a gem, don&#39;t
use a group at all.</p>

<h2 id="toc_2">Adding custom groups</h2>

<p>You can easily add other groups. For example, Rails 3.1 and up have gems in the
<code>:assets</code> group. This line from <code>config/application.rb</code> instructs Bundler to
only require the assets in development and test environments.</p>
<pre><span class="Type">Bundler</span>.require(<span class="Operator">*</span><span class="Type">Rails</span>.groups(<span class="Constant">:assets</span> =&gt; <span class="rubyStringDelimiter">%w(</span><span class="String">development test</span><span class="rubyStringDelimiter">)</span>))</pre>
<p>You can add your own groups and let Bundler require them automatically.</p>

<p>Here is an example:</p>
<pre>group <span class="Constant">:security</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">devise</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">cancan</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span>

group <span class="Constant">:monitoring</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">newrelic_rpm</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">airbrake</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span></pre>
<p>So, we want security to always be there, but monitoring only in production.
Then your configuration inside <code>config/application.rb</code> should read:</p>
<pre>groups = {
  <span class="Constant">assets</span>:     <span class="rubyStringDelimiter">%w(</span><span class="String">development test</span><span class="rubyStringDelimiter">)</span>,
  <span class="Constant">monitoring</span>: <span class="rubyStringDelimiter">%w(</span><span class="String">production</span><span class="rubyStringDelimiter">)</span>
}
<span class="Type">Bundler</span>.require(<span class="Constant">:security</span>, <span class="Operator">*</span><span class="Type">Rails</span>.groups(groups))</pre>
<p>You can group together gems per type of gem, like <code>:assets</code>, or per part of the
application, like <code>:security</code>, or <code>:backend</code>. See what makes the most sense for
your application.</p>

<h2 id="toc_3">Grouping related gems</h2>

<p>When you use Cucumber, Spinach, or Turnip, you&#39;ll end up with a set of related
gems.  When you cram all of these into the test group, they&#39;ll end up loaded in
your RSpec tests too.</p>

<p>You could create a group for this:</p>
<pre>group <span class="Constant">:cucumber</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">cucumber-rails</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">capybara</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">launchy</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">database_cleaner</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span></pre>
<p>This group won&#39;t be loaded. If you want to require these gems inside your
Cucumber tests, add this line to <code>features/support/env.rb</code>:</p>
<pre><span class="Type">Bundler</span>.require(<span class="Constant">:cucumber</span>)</pre>
<p>You could do this for other groups of related gems too. For instance, you might
have a couple of scripts or rake tasks running periodically that use gems that
you don&#39;t use in the rest of your application. With groups you can require them
at the right moment.</p>

<h2 id="toc_4">Other gems</h2>

<p>There are also some gems that are only used from the command line. An example
might be thin, or capistrano. Here are some more examples:</p>
<pre>group <span class="Constant">:capistrano</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">capistrano</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">capistrano-ext</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">capistrano_colors</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">capistrano_chef_solo</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span>

group <span class="Constant">:test_tools</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">autotest</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">spork</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">spec_coverage</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:platforms</span> =&gt; <span class="Constant">:ruby_19</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">fuubar</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">fuubar-cucumber</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span></pre>
<p>There is no need to add <code>:require =&gt; false</code> to every gem, because it won&#39;t get
loaded anyway. These gems either provide a command line tool like <code>cap</code> or
<code>autotest</code>, or they will be required manually at a specific moment, only when
they are needed.</p>

<h2 id="toc_5">Console Extensions</h2>

<p>There are a number of gems that will spice up your IRB session, like
awesome_print, hirb and wirb. You can load them inside your <code>~/.irbrc</code> file,
but if they are not present inside your Gemfile, they won&#39;t be available
inside projects using Bundler.</p>

<p>A group can play a part in solving this problem.</p>
<pre>group <span class="Constant">:console</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">wirb</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">hirb-unicode</span><span class="rubyStringDelimiter">'</span>
  gem <span class="rubyStringDelimiter">'</span><span class="String">awesome_print</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:require</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">ap</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span></pre>
<p>Now, to automatically load them in Rails, but only when opening the console,
open up <code>config/application.rb</code>.  At the top you&#39;ll find an if-statement
checking for Bundler. Inside this block, you can add this piece of code:</p>
<pre><span class="Type">Class</span>.new <span class="Type">Rails</span><span class="Operator">::</span><span class="Type">Railtie</span> <span class="rubyControl">do</span>
  console <span class="rubyControl">do</span> |<span class="Identifier">app</span>|
    <span class="Type">Bundler</span>.require(<span class="Constant">:console</span>)
    <span class="Type">Wirb</span>.start
    <span class="Type">Hirb</span>.enable
  <span class="rubyControl">end</span>
<span class="rubyControl">end</span></pre>
<p>This creates an anonymous Railtie in which you can specify what happens when
the console is started. Here you can require all your console extensions and
perform additional configuration.</p>

<p>Railties need to be loaded before you define your Rails application, or else
you&#39;re too late and the console block won&#39;t be executed.</p>
]]>
      </description>
      <guid>http://iain.nl/getting-the-most-out-of-bundler-groups</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Backends in Rails 3.1</title>
      <link>http://iain.nl/backends-in-rails-3-1</link>
      <pubDate>Sun, 31 Jul 2011 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>If you find yourself needing a backend interface, you can either get an admin plugin of the shelf, like
<a href="https://github.com/sferik/rails_admin">RailsAdmin</a> or <a href="http://activeadmin.info/">ActiveAdmin</a>, or
build your own. The of-the-shelf options provide a lot of functionality and are really worth a look.</p>

<p>You can also build your own backend. Building your own gives you maximum freedom. It requires a bit
more work, but it might be preferrable, especially if your customer also needs to work with it.</p>

<p>There are some awesome tools out there to help you build your own backend. I&#39;ll show you how I would
go about making such a backend. I&#39;m using Rails 3.1 (the rc5 at this moment) on Ruby 1.9.2. I might
gloss over some details here and there, so use your own expertise to fill in some gaps.</p>

<p>The entire backend is available on <a href="https://github.com/iain/simple-backend-example">Github</a>. I have
also published the end result on <a href="http://simple-backend-example.heroku.com/backend">Heroku</a> You can
log in with username &quot;frodo&quot; and the password &quot;thering&quot;.</p>

<h2 id="toc_0">A new application controller</h2>

<p>A backend can be seen as a different application inside your regular application. That&#39;s why I start
out with a fresh application controller, just for the backend, from which every other controller can
inherit.</p>
<pre>rails generate controller backend/application</pre>
<p>Because I don&#39;t want to be bothered by anything from the normal application controller, I choose to
inherit straight from <code>ActionController::Base</code>:</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">ApplicationController</span> &lt; <span class="Type">ActionController</span>::<span class="Type">Base</span>
  protect_from_forgery
<span class="Keyword">end</span></pre>
<p>All routes should be in the backend too. This is extremely simple. Just wrap your normal routes
inside a <code>namespace</code> block:</p>
<pre><span class="Type">SimpleBackendExample</span>::<span class="Type">Application</span>.routes.draw <span class="rubyControl">do</span>

  root <span class="Constant">to</span>: <span class="rubyStringDelimiter">"</span><span class="String">home#index</span><span class="rubyStringDelimiter">"</span>
  <span class="Comment"># other routes go here</span>

  namespace <span class="Constant">:backend</span> <span class="rubyControl">do</span>
    root <span class="Constant">to</span>: <span class="rubyStringDelimiter">"</span><span class="String">products#index</span><span class="rubyStringDelimiter">"</span>
    resources <span class="Constant">:products</span>
    resources <span class="Constant">:widgets</span>
  <span class="rubyControl">end</span>

<span class="rubyControl">end</span></pre>
<p>Now it&#39;s time to implement these resources.</p>

<h2 id="toc_1">Resources</h2>

<p>Usually, you&#39;ll need a lot of CRUD resources inside your backend. I prefer to use the
<a href="https://github.com/josevalim/inherited_resources">inherited_resources</a> gem.</p>

<p>First, make sure you install it, by adding it to your <code>Gemfile</code> and running the <code>bundle</code> command:</p>
<pre>gem <span class="rubyStringDelimiter">'</span><span class="String">inherited_resources</span><span class="rubyStringDelimiter">'</span></pre>
<p>Next, I prefer to make a base class for all resource controllers too. This is the ideal place for
configuring Inherited Resources. Every CRUD controller can inherit from this one, while other
controllers can inherit from <code>Backend::ApplicationController</code>.</p>
<pre>rails generate controller backend/resource</pre>
<p>Normally <code>inherited_resources</code> advices you to inherit from <code>InheritedResources::Base</code>. In turn,
<code>InheritedResources::Base</code> inherits from your own <code>ApplicationController</code>. But here we want to
inherit from <code>Backend::ApplicationController</code>. Luckily, we can do that:</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">ResourceController</span> &lt; <span class="Type">Backend</span>::<span class="Type">ApplicationController</span>
  inherit_resources
  respond_to <span class="Constant">:html</span>
<span class="Keyword">end</span></pre>
<p>Now, if we want to create a CRUD controller, we can do that by inheriting from
<code>Backend::ResourceController</code>.</p>
<pre>rails generate controller backend/products</pre>
<p>The controller code is now really simple:</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">ProductsController</span> &lt; <span class="Type">Backend</span>::<span class="Type">ResourceController</span>
<span class="Keyword">end</span></pre>
<h2 id="toc_2">View inheritence</h2>

<p>You&#39;re now free to make the views for every controller. This can be really boring, so it&#39;s a good
thing that Rails 3.1 ships with a feature called &#39;view inheritence&#39;. This means that if a view does
not exist, it will go up the inheritence tree to find a view to render.</p>

<p>This means that we can create some simple views for our <code>Backend::ResourceController</code> and every
resource controller can render those. Only if we want something different, we need to make a
specific view. This means though that our views need to be agnostic about the model they&#39;re
handling.</p>

<p>Inherited Resources provides a lot of helpers to make views agnostic of the model they are
rendering. In the index action you have access to <code>collection</code>, in the other actions you can
reference <code>resource</code>. There are also URL helpers like <code>resource_path</code> and <code>collection_path</code>.</p>

<p>But if we&#39;re agnostic of the model, we need to use inflection to see which fields we can render. We
can ask the <code>resource_class</code> to see what attributes are defined. This will include automatic fields
like <code>id</code>, <code>updated_at</code> and <code>created_at</code> too. But even without these fields, the list can become
a bit too long for index pages.</p>

<p>In fact, I&#39;ve found that the list of columns to display on the index page is something you want to
customize just about every time. So let&#39;s build a simple view to be overriden in every controller. In
<code>app&#47;views&#47;backend&#47;resource&#47;index.html.haml</code>, I put the following:</p>
<pre><span class="Special">=</span> render <span class="rubyStringDelimiter">"</span><span class="String">index</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">attributes</span>: attributes</pre>
<p>And add to the <code>Backend::ResourceHelper</code>:</p>
<pre><span class="Keyword">module</span> <span class="Type">Backend</span>::<span class="Type">ResourceHelper</span>

  <span class="PreProc">def</span> <span class="Function">attributes</span>
    resource_class.attribute_names - <span class="rubyStringDelimiter">%w(</span><span class="String">id created_at updated_at</span><span class="rubyStringDelimiter">)</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>This will render the index-partial with the first three attributes of the model. The
index-partial then looks like this:</p>
<pre><span class="Special">%</span><span class="Conditional">table</span>
  <span class="Special">%</span><span class="Conditional">thead</span>
    <span class="Special">%</span><span class="Conditional">tr</span>
      <span class="Special">-</span> attributes.each <span class="rubyControl">do</span> |<span class="Identifier">attr</span>|
        <span class="Special">%</span><span class="Conditional">th</span><span class="Special">=</span> resource_class.human_attribute_name(attr)
      <span class="Special">%</span><span class="Conditional">th</span> <span class="Special">&amp;nbsp;</span>
  <span class="Special">%</span><span class="Conditional">tbody</span>
    <span class="Special">-</span> collection.each <span class="rubyControl">do</span> |<span class="Identifier">resource</span>|
      <span class="Special">%</span><span class="Conditional">tr</span><span class="Delimiter">[</span>resource<span class="Delimiter">]</span>
        <span class="Special">-</span> attributes.each <span class="rubyControl">do</span> |<span class="Identifier">attr</span>|
          <span class="Special">%</span><span class="Conditional">td</span><span class="Special">=</span> resource.public_send(attr).to_s.truncate(<span class="Number">20</span>)
        <span class="Special">%</span><span class="Conditional">td</span>
          <span class="Special">=</span> link_to <span class="rubyStringDelimiter">'</span><span class="String">show</span><span class="rubyStringDelimiter">'</span>, resource_path(resource)
          |
          <span class="Special">=</span> link_to <span class="rubyStringDelimiter">'</span><span class="String">edit</span><span class="rubyStringDelimiter">'</span>, edit_resource_path(resource)
          |
          <span class="Special">=</span> link_to <span class="rubyStringDelimiter">'</span><span class="String">destroy</span><span class="rubyStringDelimiter">'</span>, resource_path(resource), <span class="Constant">method</span>: <span class="Constant">:delete</span>, <span class="Constant">confirm</span>: <span class="rubyStringDelimiter">"</span><span class="String">Are you sure?</span><span class="rubyStringDelimiter">"</span></pre>
<p>I can now easily override this per controller. If, for example, I wanted to only show the name
column for products, I could create <code>app&#47;views&#47;backend&#47;products&#47;index.html.haml</code> with only this
line:</p>
<pre><span class="Special">=</span> render <span class="rubyStringDelimiter">"</span><span class="String">index</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">attributes</span>: <span class="rubyStringDelimiter">%w(</span><span class="String">name</span><span class="rubyStringDelimiter">)</span></pre>
<p>The show action probably wants to list everything, so it&#39;ll be something like this:</p>
<pre><span class="Special">%</span><span class="Conditional">dl</span>
  <span class="Special">-</span> resource_class.attribute_names.each <span class="rubyControl">do</span> |<span class="Identifier">attr</span>|
    <span class="Special">%</span><span class="Conditional">dt</span><span class="Special">=</span> resource_class.human_attribute_name(attr)
    <span class="Special">%</span><span class="Conditional">dd</span><span class="Special">=</span> resource.public_send(attr)</pre>
<h2 id="toc_3">Simple Form</h2>

<p>My favorite gem for creating forms is <a href="https://github.com/plataformatec/simple_form">simple_form</a>.
It is really flexible. Install it, by adding it to your <code>Gemfile</code> and following the instructions in
simple_form&#39;s README.</p>

<p>Our form partial in <code>app&#47;view&#47;backend&#47;resource&#47;_form.html.haml</code> will look something like:</p>
<pre><span class="Special">=</span> simple_form_for [ <span class="Constant">:backend</span>, resource ] <span class="rubyControl">do</span> |<span class="Identifier">f</span>|
  <span class="Special">-</span> attributes.each <span class="rubyControl">do</span> |<span class="Identifier">attr</span>|
    <span class="Special">=</span> f.input attr
  <span class="Special">=</span> f.submit</pre>
<p>And the new and edit pages will simply render this partial, and look similar to the index template:</p>
<pre><span class="Special">%</span><span class="Conditional">h2</span> Edit <span class="Delimiter">#{</span>resource_class.model_name.human<span class="Delimiter">}</span>

<span class="Special">=</span> render <span class="rubyStringDelimiter">"</span><span class="String">form</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">attributes</span>: attributes</pre>
<h2 id="toc_4">Scopes &amp; Pagination</h2>

<p>For the index page, you&#39;ll need pagination too. My favorite choice is
<a href="https://github.com/amatsuda/kaminari">Kaminari</a> in combination with
<a href="https://github.com/plataformatec/has_scope">has_scope</a>:</p>
<pre>gem <span class="rubyStringDelimiter">'</span><span class="String">kaminari</span><span class="rubyStringDelimiter">'</span>
gem <span class="rubyStringDelimiter">'</span><span class="String">has_scope</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">git</span>: <span class="rubyStringDelimiter">'</span><span class="String">git://github.com/plataformatec/has_scope.git</span><span class="rubyStringDelimiter">'</span></pre>
<p>I&#39;m using the version of <code>has_scope</code> directly, because it has a fixed a deprecation error.</p>

<p>Next, implement it by adding this line to <code>Backend::ResourceController</code>:</p>
<pre>has_scope <span class="Constant">:page</span>, <span class="Constant">default</span>: <span class="Number">1</span></pre>
<p>And put it in your view as well:</p>
<pre><span class="Special">=</span> paginate collection</pre>
<p>Super easy! Don&#39;t forget to run the generators provided by kaminari to configure it further, if you want.</p>

<h2 id="toc_5">Responders</h2>

<p>To get flash messages, we&#39;ll need to create a responder. The responders gem has a generator for
this, which you should use. We&#39;ll need a small tweak to get it to work:</p>
<pre><span class="Comment"># app/controllers/backend/responder.rb</span>
<span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">Responder</span> &lt; <span class="Type">ActionController</span>::<span class="Type">Responder</span>

  <span class="PreProc">include</span> <span class="Type">Responders</span>::<span class="Type">FlashResponder</span>
  <span class="PreProc">include</span> <span class="Type">Responders</span>::<span class="Type">HttpCacheResponder</span>

  <span class="PreProc">def</span> <span class="Function">initialize</span>(*)
    <span class="Keyword">super</span>
    <span class="Identifier">@flash_now</span> = <span class="Constant">:on_failure</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>I&#39;ve renamed it to make it clearer that this is the responder for the backend only. For the reason
of the initializer, see this <a href="https://github.com/plataformatec/responders/pull/26">pull request</a>.</p>

<p>To get flash messages for validation errors, you need to customize the locale file that was
generated, to include alert messages for create and update:</p>
<pre><span class="Identifier">en</span><span class="Special">:</span>
  <span class="Identifier">flash</span><span class="Special">:</span>
    <span class="Identifier">actions</span><span class="Special">:</span>
      <span class="Identifier">create</span><span class="Special">:</span>
        <span class="Identifier">notice</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} was successfully created.</span><span class="String">'</span>
        <span class="Identifier">alert</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} could not be created.</span><span class="String">'</span>
      <span class="Identifier">update</span><span class="Special">:</span>
        <span class="Identifier">notice</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} was successfully updated.</span><span class="String">'</span>
        <span class="Identifier">alert</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} could not be updated.</span><span class="String">'</span>
      <span class="Identifier">destroy</span><span class="Special">:</span>
        <span class="Identifier">notice</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} was successfully destroyed.</span><span class="String">'</span>
        <span class="Identifier">alert</span><span class="Special">:</span> <span class="String">'</span><span class="String">%{resource_name} could not be destroyed.</span><span class="String">'</span></pre>
<p>Next, you&#39;ll need to add it to <code>Backend::ResourceController</code>, because Inherited Resources will
otherwise override it with its own responders.</p>
<pre><span class="Comment"># app/controllers/backend/resource_controller.rb</span>
<span class="Constant">self</span>.responder = <span class="Type">Backend</span>::<span class="Type">Responder</span></pre>
<p>By adding the <code>HttpCacheResponder</code>, the website speeds up quite a bit. It will set the appropriate
headers, like ETags, based on the resource you&#39;re viewing. This means that if you&#39;re viewing a page
for the second time, you don&#39;t have to render the view anymore and your Rails app only sends a <code>304
Not Modified</code> to your browser. If you&#39;re viewing my example on Heroku, you can see Varnish adding
another layer of caching on top of it, using those ETags. It makes your backend really snappy!</p>

<h2 id="toc_6">Authentication</h2>

<p>Our backend needs to be private, so we&#39;ll need some form of authentication. In most cases (more
than you&#39;d think even) basic authentication will work. This can be easily done inside the
<code>Backend::ApplicationController</code>, by adding one simple line:</p>
<pre>http_basic_authenticate_with <span class="Constant">name</span>: <span class="rubyStringDelimiter">"</span><span class="String">frodo</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">password</span>: <span class="rubyStringDelimiter">"</span><span class="String">thering</span><span class="rubyStringDelimiter">"</span></pre>
<p>If you&#39;re opting for a more complex system, with users and so on, I would go for
<a href="https://github.com/plataformatec/devise">Devise</a>. The powerful thing about Devise is that you can
really easily create a multiple types of users who have nothing with each other in common. They each
have their own tables and sign in pages.</p>

<p>You can configure Devise to use your own controllers instead of its own, so you can really separate
the admins from the rest of the system.</p>

<p>To generate administrators:</p>
<pre>rails generate devise admin</pre>
<p>Then I prefer to place the views inside the backend namespace as well. This means that I need to
recreate the controllers that Devise provides. This sounds like a lot of work, but it also means
that I can really easily customize it. Rather than depending on the customization hooks that Devise
provides (they are really good), I can override certain methods inside the controller. Devise&#39;s code
is so nice, I can easily override just the functionality I like to make it work.</p>

<p>To do this, place the <code>devise_for</code> route inside your namespace:</p>
<pre>namespace <span class="Constant">:backend</span> <span class="rubyControl">do</span>
  devise_for <span class="Constant">:admins</span>, <span class="Constant">skip</span>: <span class="Constant">:registrations</span>
<span class="rubyControl">end</span></pre>
<p>And create controllers like this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">SessionsController</span> &lt; <span class="Type">Devise</span>::<span class="Type">SessionsController</span>
  layout <span class="rubyStringDelimiter">"</span><span class="String">backend/sign_in</span><span class="rubyStringDelimiter">"</span>
<span class="Keyword">end</span></pre>
<p>As you can see, I can now easily define the backend layout inside
the controller, without having to revert to a more complex <a href="https://github.com/plataformatec/devise/wiki/How-To:-Create-custom-layouts">hook
method</a>. Remember
that, due to view inheritance, you don&#39;t need to install the views. The original views that Devise
provides are in the inheritence tree, so they will be rendered if you don&#39;t provide your own.</p>

<p>And don&#39;t forget to activate the authentication to every controller in the backend, by adding to
your <code>Backend::ApplicationController</code>:</p>
<pre>before_filter <span class="Constant">:authenticate_admin!</span></pre>
<p>Personally, I would try to avoid going with Devise and stick to basic authentication as long as
possible. That&#39;s also one of the main reasons I don&#39;t tend to go with the of the shelf admin
solutions. They require Devise. It adds a lot of overhead that I don&#39;t usually need. You might also
want to check out the <a href="http://railscasts.com/episodes/270-authentication-in-rails-3-1">Railscast</a> on
creating your own authentication system.</p>

<h2 id="toc_7">Styling</h2>

<p><strong>Update</strong> I&#39;ve switched to using the <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>
styling. It&#39;s a lot prettier and cleaner than wep-app-theme. Have a look at <a href="https://github.com/iain/simple-backend-example/commit/0a9f5a8ab5e9a82ce90c092aab2b628211f7036b">this
commit</a>
to see what I&#39;ve had to do. You can skip this chapter if you like now.</p>

<p>So, we now have a nice backend system in place. But it still looks ugly. Time
to add some style! Let&#39;s get something of-the-shelf to get going. I like
<a href="https://github.com/pilu/web-app-theme">web-app-theme</a>. This will make our backend look just like
RailsAdmin.</p>

<p>The easiest way to get a theme, I found, is to just clone web-app-theme somewhere and copy over the
files you need. Rails 3.1 has the asset pipeline, so this means we can have a nice spot to put them:
in the <code>vendor&#47;assets</code> directory.</p>
<pre><span class="Statement">mkdir</span> <span class="Special">-p</span> vendor/assets/stylesheets/web-app-theme
cp ../web-app-theme/stylesheets/base.css vendor/assets/stylesheets/web-app-theme/
cp ../web-app-theme/stylesheets/themes/default/style.css vendor/assets/stylesheets/web-app-theme
cp <span class="Special">-r</span> ../web-app-theme/stylesheets/themes/default/images vendor/assets
cp <span class="Special">-r</span> ../web-app-theme/stylesheets/themes/default/fonts public</pre>
<p>You need to change styles.css a bit to change the paths to images and any custom fonts. In Rails
3.1, assets aren&#39;t located in an <code>images</code> directory, but in <code>&#47;assets</code>. Fonts are not served through
Rails, so those should go inside the <code>public</code> directory. A quick find and replace should do the
trick just fine.</p>

<p>Next up is the layout. You can install web-app-theme as a gem in your project and let
it generate the layout for you. This is not necessary. You can find a layout inside
<code>lib&#47;generators&#47;web_app_theme&#47;theme&#47;templates&#47;layout_admin.html.erb</code>. Copy it to
<code>app&#47;views&#47;layouts&#47;backend&#47;application.html.erb</code>. Remember, view inheritance will automatically pick
it up for every controller in the backend. I&#39;m a Haml user, so I converted it using <code>html2haml</code>:</p>
<pre>gem <span class="Statement">install</span> hpricot ruby_parser
<span class="Statement">mkdir</span> <span class="Special">-p</span> app/views/layouts/backend
html2haml ../web-app-theme/lib/web_app_theme/theme/layout_admin.html.erb <span class="Operator">&gt;</span> app/views/layouts/backend/application.html.haml</pre>
<p>You have some cleaning up to do. Or just <a href="https://github.com/iain/simple-backend-example/blob/master/app/views/layouts/backend/application.html.haml">grab the
one</a>
I&#39;ve already made! Afterwards, look at the classes web-app-theme uses and apply it to
your views as well.</p>

<p>To include the stylesheets, I just include one inside the layout:</p>
<pre><span class="Special">=</span> stylesheet_link_tag <span class="rubyStringDelimiter">"</span><span class="String">backend</span><span class="rubyStringDelimiter">"</span></pre>
<p>In <code>app&#47;assets&#47;stylesheets&#47;backend.css</code>, I use the awesome power of Sprockets to include the rest:</p>
<pre><span class="Comment">/*</span>
<span class="Comment"> *= require web-app-theme/base</span>
<span class="Comment"> *= require web-app-theme/style</span>
<span class="Comment"> *= require_tree ./backend</span>
<span class="Comment"> */</span></pre>
<p>It also includes every css file I have inside the <code>app&#47;assets&#47;stylesheets&#47;backend</code> directory, which
is where future customizations will go.</p>

<p>I also use the same structure for javascripts, creating the following
<code>app&#47;assets&#47;javascripts&#47;backend.js</code>:</p>
<pre><span class="Comment">//= require jquery</span>
<span class="Comment">//= require jquery_ujs</span>
<span class="Comment">//= require_tree ./backend</span></pre>
<p>This styling would give you enough to start your backend. There are a ton of customizations you can
do, but I&#39;ll leave that up to you.</p>

<h2 id="toc_8">More namespacing</h2>

<p>Because of the way namespacing works, you can customize your models for use in the backend. This
allows you to add methods for use in the backend only, without cluttering your classes in the rest
of the application.</p>
<pre><span class="Comment"># app/models/product.rb</span>
<span class="Keyword">class</span> <span class="Type">Product</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  has_many <span class="Constant">:widgets</span>
<span class="Keyword">end</span>

<span class="Comment"># app/models/backend/product.rb</span>
<span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">Product</span> &lt; ::<span class="Type">Product</span>

  <span class="PreProc">def</span> <span class="Function">deactivate_all_widgets</span>
    widgets.each(&amp;<span class="Constant">:deactivate</span>)
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>Because Inherited Resources is in the Backend namespace, it will use this class instead of the normal
one.</p>

<p>You can also make use of lexical scoping to implicitly reference the namespaced classes. This is
quite subtle, so it&#39;s a bit error-prone.</p>

<p>In the following example, <code>@product</code> will be an instance of <code>Backend::Product</code>:</p>
<pre><span class="Keyword">module</span> <span class="Type">Backend</span>
  <span class="Keyword">class</span> <span class="Type">ProductsController</span>
    <span class="PreProc">def</span> <span class="Function">new</span>
      <span class="Identifier">@product</span> = <span class="Type">Product</span>.new
    <span class="PreProc">end</span>
  <span class="Keyword">end</span>
<span class="Keyword">end</span></pre>
<p>In the next example, <code>@product</code> will be an instance of <code>::Product</code>, because only the <code>class</code> and
<code>module</code> keywords will create the scope for you. You are scoped inside
<code>Backend::ProductsController</code>, but not really inside <code>Backend</code>.</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">ProductsController</span>
  <span class="PreProc">def</span> <span class="Function">new</span>
    <span class="Identifier">@product</span> = <span class="Type">Product</span>.new
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Also, you don&#39;t need to explicitly tell the form that its resource needs to be scoped to the
backend. There are a lot of tiny nuances that change when you go this route. So beware. Ruby&#39;s
namespacing is powerful, but combined with Rails&#39; naming conventions it can also be a bit confusing
at times.</p>

<h2 id="toc_9">Conclusion</h2>

<p>Making your own backend is really easy. Sure, there are out of the box gems that do all this for
you and more. But if you want more control, yet still get some of the productivity, Rails 3.1 has all the
tools to make it work. All the gems I&#39;ve used fit nicely together. Sure, most of them are
made by <a href="http://twitter.com/josevalim">José Valim</a>, or by his company
<a href="http://www.plataformatec.com.br/en/">Plataforma</a>, but it shows how extensible the Rails platform really
is.</p>

<p>Whether to choose for a custom solution or something more automatic is something you should decide
on a per-project basis. If you&#39;re building it for non-technical customers, doing it yourself might
be the better solution. But products like RailsAdmin give so much nice features, you&#39;d better make
sure.</p>
]]>
      </description>
      <guid>http://iain.nl/backends-in-rails-3-1</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Cucumber vs. Steak</title>
      <link>http://iain.nl/cucumber-vs-steak</link>
      <pubDate>Mon, 31 Jan 2011 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><a href="http://jeffkreeftmeijer.com">Jeff Kreeftmeijer</a> talked about <a href="http://cukes.info/">Cucumber</a>
and <a href="https://github.com/cavalle/steak">Steak</a> at the last <a href="http://amsterdam-rb.org/">Amsterdam Ruby
Meetup</a>. He hit upon an important theme in software development:
<strong>reducing complexity</strong>; in this case the extra layers of complexity introduced by Cucumber
features and step definitions. And he&#39;s absolutely right. If you don&#39;t need the natural
language Cucumber provides, then you should get rid of the extra complexity and <a href="http://jeffkreeftmeijer.com/2010/steak-because-cucumber-is-for-vegetarians/">use Steak
instead</a>.</p>

<p>As much as I agree with this, I think there is a way of using Cucumber that makes it a valid option
to use it in more cases than you think. It&#39;s for doing Behavior Driven Development with a high focus
on the problem you&#39;re trying to solve. Let me explain what I mean by this.</p>

<h3 id="toc_0">Using steak for integration tests</h3>

<p>Most examples of Cucumber use the <a href="https://github.com/aslakhellesoy/cucumber-rails/blob/master/templates/install/step_definition%0As/capybara_steps.rb.erb">web
steps</a> that the generator of cucumber-rails provides. These are fairly low level:
click a link, fill in some fields, submit and check the outcome. Writing features like this is easy.
All the parts are present by default, so you can get some work done quickly. But if you do it like
this, there is no reason why you should use Cucumber. You&#39;re adding complexity (features and step
definitions) which don&#39;t add anything compared to Steak.</p>

<p>In fact, Ruby is a very clean language, and the <a href="https://github.com/jnicklas/capybara/">Capybara</a>
API is very clean too. Even if you have a customer that wants to read your features, they can
read and write for Steak as well, with very little extra effort. So, if you&#39;re only in it for the
integration testing, Cucumber will only make your life more complex. And we don&#39;t want this extra
complexity, unless there is a good reason for it.</p>

<h3 id="toc_1">On behavior and implementation</h3>

<p>But there is more to writing acceptance tests, or doing BDD and TDD. One of the more interesting
parts is to discover the design of your code (or the structure of your application). To do this in
unit tests, you need to focus on <strong>behavior</strong>, rather than implementation.</p>

<p>For example: this means that you don&#39;t want to test if the results are an empty array, but you
should just test that it is empty. The fact that you happened to have implemented this with an array
is not important.</p>
<pre>it { should == []    } <span class="Comment"># bad: testing implementation</span>
it { should be_empty } <span class="Comment"># good: testing the behavior</span></pre>
<p>The same is true for Cucumber. But here we mostly care about the behavior for the feature. Not the
fact that you happened to have implemented it as a website with links and buttons. Take a look at
the very first example the <a href="http://www.pragprog.com/titles/achbd/the-rspec-book">RSpec book</a> gives
of Cucumber:</p>
<pre><span class="PreProc">Feature:</span> pay bill on-line
  In order to reduce the time I spend paying bills
  As a bank customer with a checking account
  I want to pay my bills on-line

  <span class="PreProc">Scenario:</span> pay a bill
    <span class="Conditional">Given</span> checking account with $50
    <span class="Conditional">And</span> a payee named Acme
    <span class="Conditional">And</span> an Acme bill for $37
    <span class="Function">When</span> I pay the Acme bill
    <span class="Type">Then</span> I should have $13 remaining in my checking account
    <span class="Type">And</span> the payment of $37 to Acme should be listed in Recent Payments</pre>
<p>There are no implementation details here. No following links, no filling in fields, no pressing
buttons. This is in my opinion the biggest reason to use Cucumber. It focusses you to towards what
you are actually trying to achieve. The step definitions are here to fill in the details.</p>

<p>When you use Cucumber this way, it opens the way for real BDD. You&#39;re describing what you want
to achieve, not <em>how</em> you want to achieve it. This is in my opinion the unique selling point of
Cucumber. It&#39;s a very nice framework to separate the implementation from your intention. <strong>Focussing
on your intentions (in a way that can be automated) is the essence of BDD.</strong></p>

<h3 id="toc_2">But why do this in a natural language?</h3>

<p>You could also do this with Steak of course. It&#39;s just Ruby, so you could add some code to hide some
of the details to helper methods. And because it is Ruby, you&#39;re probably tempted to do it earlier
than with Cucumber. You are now programming, so your programming instincts will come in to play,
making the features clean and simple. We do this all the time. So why should you write in a natural
language?</p>

<p>You&#39;re doing it human language, so write it down in the same way you are talking about it. Think
about how you would explain using the website to the stakeholder of the feature. It doesn&#39;t matter
that the stakeholder doesn&#39;t care about your nifty cucumber features. How would (s)he explain it to
you?</p>

<p>Also, the natural language is closer to your understanding of the problem you&#39;re trying to
solve. When I write in code, my programmer side becomes active. My programmer side is focussed
on solutions. But I want to <strong>delay the solution</strong> as long as I can, until we have a decent
understanding of the problem. So by not writing in code, you can focus more on the problem, rather
than on the solution.</p>

<p>Cucumber provides a hard boundary. Your intent is in the feature files, your implementation is
in step definitions. And it is helpful in doing this too; it provides you with the right step
definition when it encounters something that it doesn&#39;t know yet. It&#39;s really easy to keep the
feature files clean and simple. I will grant you that organizing your step definitions requires a
fair bit of OCD.</p>

<p>Make no mistakes about it: it isn&#39;t easy. It&#39;s very hard to figure out the right way of describing
your problem, using the right language and in such a way that Cucumber can make sense of it too.
But that is what is to be expected. If your problem is hard, than trying to figure out what your
problem entails and describing it in a way that isn&#39;t ambiguous, should to be hard too. But you
should make the effort to really get the language right, because <strong>the implementation that follows
will reflect the way you&#39;ve described it earlier</strong>. And besides, if it wasn&#39;t hard, than it wouldn&#39;t
be interesting, now would it?</p>

<h3 id="toc_3">Closing thoughts</h3>

<p>I&#39;m not saying that you shouldn&#39;t use Steak. You should test your application from start to finish,
from top to bottom. I don&#39;t care what tools you use, as long as you <strong>test all the fucking time</strong>.
If one of these tools is keeping you from doing that, than you shouldn&#39;t use it. If you find writing
Cucumber features depressing, then obviously you shouldn&#39;t use it. These tools are here to help us,
not the other way around.</p>

<p>That being said, I think Cucumber can help me in coming up with the right solution to the problem,
documenting what my application is all about and testing it, all at the same time. I like that and
that&#39;s why I&#39;ll continue to use Cucumber, even for my own projects where I am the only one reading
the features.</p>

<p>And remember, when doing BDD with Cucumber: &quot;When you’re writing a new scenario, I recommend
you start with the formulation of the desired outcome. Write the Then steps first. Then
write the When step to discover the action&#47;operation and finally write the Given steps
that need to be in place in order for the When&#47;Then to make sense.&quot; (from the <a href="https://github.com/aslakhellesoy/cucumber/wiki/">Cucumber
wiki</a>)</p>

<h3 id="toc_4">More information</h3>

<p>Looking around to see other people writing Cucumber stories is very educational. Have a
look at <a href="http://relishapp.com/rspec/">RSpec&#39;s features on Relish</a>. On writing good steps,
you should read up on <a href="http://elabs.se/blog/15-you-re-cuking-it-wrong">cuking it wrong</a> and
<a href="http://mislav.uniqpath.com/2010/09/cuking-it-right/">cuking it right</a>. Also, Hashrocket has an
<a href="http://hashrocket.com/blog/view/cucumber-at-hashrocket-bookclub/">interesting discussion online</a>
about how they use Cucumber. Jeff Kreeftmeijer wrote <a href="http://jeffkreeftmeijer.com/2010/steak-because-cucumber-is-for-vegetarians/">a great introduction on
Steak</a>. And finally,
the <a href="http://www.pragprog.com/titles/achbd/the-rspec-book">RSpec book</a> is really gives a good insight
into how to use Cucumber the right way.</p>

<p>Also, Dan North wrote a lengthy article on <a href="http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/">how to write
stories</a>, making a similar point.</p>
]]>
      </description>
      <guid>http://iain.nl/cucumber-vs-steak</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Easier MetricFu with Metrical</title>
      <link>http://iain.nl/easier-metricfu-with-metrical</link>
      <pubDate>Sat, 27 Nov 2010 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>TL;DR:</strong> I&#39;ve just released <strong><a href="http://github.com/iain/metrical">metrical</a></strong>. It is a tiny wrapper
around metric_fu.</p>

<p>MetricFu is awesome. It helps me keep my code clean by identifying problem spots in my code.
Unfortunately, it&#39;s difficult to get running. MetricFu requires to be run with Rake. But by doing
that, it becomes part of your project&#39;s dependencies. Especially if you&#39;re using Bundler.</p>

<h3 id="toc_0">Enter Metrical</h3>

<p>Metrical is a wrapper around MetricFu, that allows it to be run as an executable on any project.
Just install it, and run it. No setup or adjustments to your project should be required. It&#39;s that
easy!</p>
<pre><span class="Statement">cd</span> /path/to/project/
gem <span class="Statement">install</span> metrical
metrical</pre>
<p>If you want to configure MetricFu, you can add a file called <tt>.metrics</tt>, in which you
can add your regular configuration. For all configuration options, you can visit the <a href="http://metric-fu.rubyforge.org">MetricFu
homepage</a>. All I&#39;ve done is add a small tweak to the rcov options,
so it&#39;ll run RSpec without problems.</p>

<p>So, give it a spin and tell me what you think of it!</p>
]]>
      </description>
      <guid>http://iain.nl/easier-metricfu-with-metrical</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>RSpec Array Matcher</title>
      <link>http://iain.nl/rspec-array-matcher</link>
      <pubDate>Sat, 30 Oct 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>If you&#39;re testing arrays a lot, like ActiveRecord&#39;s (named) scopes, you should know the following RSpec matcher: <code>=~</code>. It doesn&#39;t care about sorting and it gives you all the output you need when the spec fails. Here is an example:</p>
<pre>describe <span class="rubyStringDelimiter">"</span><span class="String">array matching</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>

  it <span class="rubyStringDelimiter">"</span><span class="String">should pass</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
    [ <span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span> ].should =~ [ <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">1</span> ]
  <span class="rubyControl">end</span>

  it <span class="rubyStringDelimiter">"</span><span class="String">should fail</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
    [ <span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span> ].should =~ [ <span class="Number">4</span>, <span class="Number">2</span>, <span class="Number">3</span> ]
  <span class="rubyControl">end</span>

<span class="rubyControl">end</span></pre>
<figure class="ir_black"><img src="/rspec-array-matcher-result.png" alt="" title="rspec array matcher result" width="392" height="229"></figure>

<p>Note: There is no inverse (should_not) version of this matcher.</p>
]]>
      </description>
      <guid>http://iain.nl/rspec-array-matcher</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Your argument doesn't cut wood</title>
      <link>http://iain.nl/your-argument-doesnt-cut-wood</link>
      <pubDate>Sat, 11 Sep 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>About once a month I read an article on comparing Ruby to another programming language. Usually it makes the point that Ruby is dynamic and open and therefore it is less suited for reliable applications for big companies with big needs.</p>

<p>To me this sounds like a professional carpenter saying that a chainsaw is less useful for making big things because you can hurt yourself with it or make a big mistake more easily. While it might be true that these things can and do happen, it&#39;s not a definitive reason not to use it. And while other tools might be better at a certain task, it can still do the job just fine.</p>

<p>With great power comes great responsibility. I cannot lecture you on the precautions you need to take when using power tools, but when it comes to software development the things you need to do is testing and refactoring. I believe this to be true for every programming language, just as you always need to be careful you don&#39;t hurt yourself or others when you saw something, no matter which kind of saw you use.</p>

<p>I don&#39;t consider Java to be a screwdriver, Ruby to be a saw and Python to be a hammer. Choosing the right tool for the right job is correct, but when it comes to programming languages, the tools aren&#39;t that different from each other. They&#39;re more like different kind of saws. They can all be used for cutting things in half. It&#39;s the skill of the person wielding the tools that makes the difference.</p>

<p>Analogies will take you only so far. They all break down at a certain point. I&#39;ve already taken this one too far for its own good. The bottom line: I like reading about interesting stuff people do in software development, no matter which language. It&#39;s all cool! Stop trying to put them into an ordered list of greatness and use your knowledge to educate and inspire us!</p>
]]>
      </description>
      <guid>http://iain.nl/your-argument-doesnt-cut-wood</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Gemfile vim syntax file</title>
      <link>http://iain.nl/gemfile-vim-syntax-file</link>
      <pubDate>Sun, 05 Sep 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I&#39;ve updated my Gemfile syntax file, adding a dash of color and making sure it supports all elements of the <a href="http://gembundler.com">Bundler</a> DSL. You can get it <a href="http://github.com/iain/osx_settings/blob/master/.vim/syntax/Gemfile.vim">here</a>. You&#39;ll also need to tell vim to automatically use it when opening a Gemfile by adding <a href="http://github.com/iain/osx_settings/blob/master/.vim/ftdetect/Gemfile.vim">this file</a>.</p>

<p>This is how it looks with the <a href="http://github.com/iain/osx_settings/blob/master/.vim/colors/ir_black.vim">ir_black</a> colorscheme:</p>

<pre class="ir_black"><font color="#96cbfe">source</font>&nbsp;<font color="#99cc99">:rubygems</font>
<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">rails</font><font color="#336633">'</font>
<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">hoptoad_notifier</font><font color="#336633">'</font>
<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">newrelic_rpm</font><font color="#336633">'</font>, <font color="#99cc99">:require</font>&nbsp;=&gt; <font color="#99cc99">false</font>
<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">mysql2</font><font color="#336633">'</font>
<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">devise</font><font color="#336633">'</font>

<font color="#7c7c7c"># ... etc ...</font>

<font color="#96cbfe">platforms</font>&nbsp;<font color="#99cc99">:ruby_18</font>&nbsp;<font color="#6699cc">do</font>
&nbsp;&nbsp;<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">system_timer</font><font color="#336633">'</font>
&nbsp;&nbsp;<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">fastercsv</font><font color="#336633">'</font>
<font color="#6699cc">end</font>

<font color="#96cbfe">group</font>&nbsp;<font color="#99cc99">:development</font>, <font color="#99cc99">:test</font>&nbsp;<font color="#6699cc">do</font>
&nbsp;&nbsp;<font color="#ffd2a7">gem</font>&nbsp;<font color="#336633">'</font><font color="#a8ff60">rspec-rails</font><font color="#336633">'</font>, <font color="#336633">'</font><font color="#a8ff60">2.0.0.beta.20</font><font color="#336633">'</font>
<font color="#6699cc">end</font></pre>

<p>Enjoy!</p>
]]>
      </description>
      <guid>http://iain.nl/gemfile-vim-syntax-file</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Building Blocks of DDD: Services</title>
      <link>http://iain.nl/building-blocks-of-ddd-services</link>
      <pubDate>Mon, 23 Aug 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>As <a href="/domain-driven-design-building-blocks-in-ruby">promised</a>, here is an example of how to use the idea of services from Domain Driven Design to help you design your code better. Let&#39;s start with some theoretical stuff, before we dive into some example code.</p>

<h3 id="toc_0">In Theory</h3>

<p>Services are best defined by what they&#39;re not. They&#39;re not entities or value objects.  To recap: entities are identifiable objects, that have real meaning in your domain. This might be a user or a post (if you&#39;re making a blog). Value objects are objects that are not defined by their identity, but by their value. An address of a person is usually a good example. It doesn&#39;t matter which address object it really is, as long as it contains the data it is supposed to have. Services are none of these. Services do something with the entities in your domain.</p>

<p>A good example of services are classes. By their very nature, classes are services for initializing objects. In Ruby this is idea is emphasized by the fact that classes are objects too. They have state and behavior, just as any other Ruby object. But their behavior is always aimed at something else, not themselves. Services tend to have no state, or very little at the most.</p>

<p>What&#39;s the advantage of thinking of classes as being services? Well, in my opinion it leads you to organize your code better. Class methods are only allowed to do something with creating instances of that class. If they are not doing that, they shouldn&#39;t be class methods.</p>

<p>It also answers the question: where should this behavior go? If it&#39;s not obvious, it&#39;s probably a service. The &#39;fat model, skinny controller&#39;-principle has gotten some news lately. This principle was invented because developers (me included) were putting too much logic into the controllers. It made the controllers skinny and readable; but it had the side affect that everybody jammed the behavior into their models (entities), making them big and unwieldy. Services will help you create small and manageable classes.</p>

<h3 id="toc_1">In Practice</h3>

<p>Time for an example. Suppose you have an admin interface which allows the user to find their entities in many different ways, filtering on attributes and ordering them around until he finds the entities he wants. It might be part of a advanced search box. This filtering business is an excellent candidate for a service.</p>

<p>There are many ways of making a filter service. I&#39;ve made something similar to this recently. I&#39;ll start by making a basic filter, with nothing specific.</p>
<pre><span class="Keyword">module</span> <span class="Type">Filter</span>
  <span class="Keyword">class</span> <span class="Type">Base</span>

    class_inheritable_array <span class="Constant">:filters</span>
    <span class="Constant">self</span>.filters = []

    <span class="Comment"># Call filter to define which filters are available.</span>
    <span class="Comment"># These will all be run in the order you specified</span>
    <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">filter</span>(*filters)
      <span class="Constant">self</span>.filters.unshift(*filters)
    <span class="PreProc">end</span>

    <span class="Comment"># The params are the parameters you might have entered in your form.</span>
    <span class="Statement">attr_reader</span> <span class="Constant">:params</span>
    <span class="PreProc">def</span> <span class="Function">initialize</span>(params)
      <span class="Identifier">@params</span> = params
    <span class="PreProc">end</span>

    <span class="Comment"># Get all filtered results. This is the public facing method that</span>
    <span class="Comment"># you'd want to call when getting the results of the filter.</span>
    <span class="PreProc">def</span> <span class="Function">all</span>
      apply_filters
      scope
    <span class="PreProc">end</span>

    <span class="Statement">private</span>

    <span class="Comment"># As part of the contract, set the default scope by overriding this method.</span>
    <span class="PreProc">def</span> <span class="Function">scope</span>
      <span class="Statement">raise</span> <span class="Type">NotImplementedError</span>
    <span class="PreProc">end</span>

    <span class="Comment"># Run all the filters, specified in subclasses.</span>
    <span class="PreProc">def</span> <span class="Function">apply_filters</span>
      filters.each { |<span class="Identifier">filter</span>| send(filter) }
    <span class="PreProc">end</span>

    <span class="Comment"># Probably every filter should be able to paginate the results.</span>
    <span class="Comment"># remember to call pagination last, because will_paginate won't return</span>
    <span class="Comment"># a real ActiveRecord::Relation object.</span>
    <span class="PreProc">def</span> <span class="Function">pagination</span>
      <span class="Identifier">@scope</span> = scope.paginate(<span class="Constant">:page</span> =&gt; page, <span class="Constant">:per_page</span> =&gt; per_page)
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">page</span>
      params[<span class="Constant">:page</span>] || <span class="Number">1</span>
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">per_page</span>
      params[<span class="Constant">:per_page</span>] || <span class="Number">20</span>
    <span class="PreProc">end</span>

    <span class="Comment"># Similar to pagination, sorting is something common to all filters,</span>
    <span class="Comment"># The default order is :id, because that will be available on every</span>
    <span class="Comment"># model. You can override it easily however.</span>
    <span class="PreProc">def</span> <span class="Function">sort</span>(default = <span class="Constant">:id</span>)
      <span class="Identifier">@scope</span> = scope.order(params[<span class="Constant">:order</span>] || default)
      <span class="Identifier">@scope</span> = scope.reverse_order <span class="Conditional">if</span> params[<span class="Constant">:direction</span>] == <span class="rubyStringDelimiter">'</span><span class="String">desc</span><span class="rubyStringDelimiter">'</span>
    <span class="PreProc">end</span>

  <span class="Keyword">end</span>
<span class="Keyword">end</span></pre>
<p>Now, you can make filters for every model. This means creating a class that inherits from this base class and implementing the simple contract we put in place. I&#39;ll use the (t)rusty Post model as an example implementation.</p>
<pre><span class="Keyword">module</span> <span class="Type">Filter</span>
  <span class="Keyword">class</span> <span class="Type">Posts</span> &lt; <span class="Type">Base</span>

    <span class="Comment"># Here I define the filter methods that will be used for posts.</span>
    filter <span class="Constant">:published</span>, <span class="Constant">:by_name</span>, <span class="Constant">:sort</span>, <span class="Constant">:pagination</span>

    <span class="Comment"># The default scope for posts is a plain Post class without any scope added.</span>
    <span class="Comment"># You can apply some permissions here, for instance.</span>
    <span class="PreProc">def</span> <span class="Function">scope</span>
      <span class="Identifier">@scope</span> ||= ::<span class="Type">Post</span>
    <span class="PreProc">end</span>

    <span class="Comment"># Only show published posts, when the 'only_published' checkbox has been</span>
    <span class="Comment"># checked in the form.</span>
    <span class="PreProc">def</span> <span class="Function">published</span>
      <span class="Identifier">@scope</span> = scope.published <span class="Conditional">if</span> params[<span class="Constant">:only_published</span>] == <span class="rubyStringDelimiter">'</span><span class="String">1</span><span class="rubyStringDelimiter">'</span>
    <span class="PreProc">end</span>

    <span class="Comment"># Provide a simple name field to filter on the name of the post</span>
    <span class="PreProc">def</span> <span class="Function">by_name</span>
      <span class="Conditional">if</span> params[<span class="Constant">:name</span>].present?
        <span class="Identifier">@scope</span> = scope.where(<span class="rubyStringDelimiter">'</span><span class="String">name LIKE ?</span><span class="rubyStringDelimiter">'</span>, <span class="rubyStringDelimiter">"</span><span class="String">%</span><span class="rubyInterpolationDelimiter">#{</span>params[<span class="Constant">:name</span>]<span class="rubyInterpolationDelimiter">}</span><span class="String">%</span><span class="rubyStringDelimiter">"</span>)
      <span class="Conditional">end</span>
    <span class="PreProc">end</span>

    <span class="Comment"># I want to sort by the published_at column by default</span>
    <span class="PreProc">def</span> <span class="Function">sort</span>(default = <span class="Constant">:published_at</span>)
      <span class="Keyword">super</span>(default)
    <span class="PreProc">end</span>

  <span class="Keyword">end</span>
<span class="Keyword">end</span></pre>
<p>To use this filter, call it from the controller:</p>
<pre><span class="Keyword">class</span> <span class="Type">Backend</span>::<span class="Type">PostsController</span> &lt; <span class="Type">ApplicationController</span>

  respond_to <span class="Constant">:html</span>, <span class="Constant">:json</span>, <span class="Constant">:xml</span>

  <span class="PreProc">def</span> <span class="Function">index</span>
    <span class="Identifier">@posts</span> = <span class="Type">Filter</span>::<span class="Type">Posts</span>.new(params[<span class="Constant">:filter</span>]).all
    respond_with <span class="Identifier">@posts</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>As you can see, this places the logic of filtering in its proper place. It&#39;s not part of the model, since it&#39;s not part of initializing objects, or behavior of individual post objects. It&#39;s a separate service, doing something with something else.</p>

<p>These services are incredibly easy to make. Just think about the objects it&#39;s trying to handle. These are probably the arguments of your initializer. Store those methods with an instance variable. All methods you create do something with either these objects or call methods that do so.</p>

<p>Don&#39;t forget to run <a href="http://wiki.github.com/kevinrutherford/reek/">reek</a> on your code to see if you have any Low Cohesion or Feature Envy warnings. If you get any, than that method probably doesn&#39;t belong here, or you&#39;ve got you&#39;re initial parameters wrong.</p>

<h11 id="toc_30055936">Some bonus material</h3>

<p>If you wish to simplify the interface even further, you can create a class method on the service to make it even easier (that&#39;s a service to create a service, so to speak).</p>
<pre><span class="Keyword">module</span> <span class="Type">Filter</span>
  <span class="Keyword">class</span> <span class="Type">Base</span>

    <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">all</span>(*args)
      new(*args).all
    <span class="PreProc">end</span>

    <span class="Comment"># ... rest of the base class ...</span>

  <span class="Keyword">end</span>
<span class="Keyword">end</span></pre>
<p>This reduces the connascence needed to use the service. Not really needed here, but it&#39;s a nice way of cleaning up your interface.</p>

<p>You might ask where do I put this into my Rails application. I make a folder <code>app&#47;services</code> and (because I use RSpec) a folder named <code>spec&#47;services</code>. If you use autotest, you need to tell it to pick up changes in these directories. You&#39;ll need to add the file <code>.autotest</code> to your application root folder, containing this bit of code to do the mapping:</p>
<pre><span class="Type">Autotest</span>.add_hook <span class="Constant">:initialize</span> <span class="rubyControl">do</span> |<span class="Identifier">at</span>|
  at.add_mapping(<span class="rubyRegexpDelimiter">%r%</span><span class="Special">^</span><span class="rubyRegexp">spec/</span><span class="Special">(</span><span class="Special">.</span><span class="Special">*</span><span class="Special">)</span><span class="rubyRegexp">_spec</span><span class="Special">\.</span><span class="rubyRegexp">rb</span><span class="Special">$</span><span class="rubyRegexpDelimiter">%</span>) { |<span class="Identifier">filename</span>, <span class="Identifier">_</span>| filename }
  at.add_mapping(<span class="rubyRegexpDelimiter">%r%</span><span class="Special">^</span><span class="rubyRegexp">app/</span><span class="Special">(</span><span class="Special">.</span><span class="Special">*</span><span class="Special">)</span><span class="Special">\.</span><span class="rubyRegexp">rb</span><span class="Special">$</span><span class="rubyRegexpDelimiter">%</span>) { |<span class="Identifier">_</span>, <span class="Identifier">m</span>| [<span class="rubyStringDelimiter">"</span><span class="String">spec/</span><span class="rubyInterpolationDelimiter">#{</span>m[<span class="Number">1</span>]<span class="rubyInterpolationDelimiter">}</span><span class="String">_spec.rb</span><span class="rubyStringDelimiter">"</span>] }
<span class="rubyControl">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/building-blocks-of-ddd-services</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Domain Driven Design: Building Blocks in Ruby</title>
      <link>http://iain.nl/domain-driven-design-building-blocks-in-ruby</link>
      <pubDate>Sun, 25 Jul 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>A few weeks ago I talked about Domain Driven Design in Ruby at the local Ruby user group:
<a href="http://rotterdam-rb.org/">Rotterdam.rb</a>. It had a great turnup (even though the weather
prevented some from coming) and there was a good discussion going on. Thank you for that! Follow
<a href="http://twitter.com/rotterdamrb">@rotterdamrb</a> to hear about future meetups with free beer and
pizza, sponsored by <a href="http://finalist.nl/">Finalist IT Group</a>!</p>

<p>It was a long talk, so I couldn&#39;t cover all the topics I wanted to cover. I talked about
ubiquitous language, bounded contexts, core and support domains, and showed some ways to do
this in Ruby, using modules. Basically, I concentrated on techniques to organize <a href="http://en.wikipedia.org/wiki/Essential_complexity">essential
complexity</a>, while keeping an eye on practical
usage with Ruby and Rails.</p>

<p>When you talk about <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven
Design</a>, you
hardly cannot do that without mentioning the three types of objects that Eric Evans discusses in his
book. It&#39;s Entity objects, Value objects and Service objects. Still I managed to do just that. Time
to fix it; here is what I failed to mention.</p>

<h3 id="toc_0">Entities</h3>

<p>Entity objects are objects that represent something in the real world and can be referenced as such.
Translated into Rails terms these would be instances of (most of) your models. You can reference a
post instance by getting it via its id from the database.</p>

<p>These objects are prime candidates for using plugins like
<a href="http://norman.github.com/friendly_id/">friendly_id</a>, making the fact that these objects have a
real identity in real life clearer. This is because you can now reference them by name, instead
of some database id. To use friendly_id with Rails 3, point your gemfile to the <a href="https://github.com/norman/friendly_id/tree/edge">&#39;edge&#39; branch on
github</a>.</p>

<h3 id="toc_1">Value Objects</h3>

<p>Objects that don&#39;t have any real identity are called &quot;Value objects&quot;. Any object that is a value
object has no real identity, nor is it important to know its identity.</p>

<p>Addresses are a good example. The value of the address (e.g. street, house number, city, country)
is important. But it&#39;s less obvious to store this in a database and reference it by an id. This id
would be purely superficial and have no meaning in the domain you are designing.</p>

<p>A pure Ruby way to do this with Structs, which I have mentioned before on
this blog. If you&#39;re using a document based database, like MongoDB, these
would obviously be embedded documents. With ActiveRecord you can use the
<a href="http://apidock.com/rails/ActiveRecord/Aggregations/ClassMethods/composed_of"><code>composed_of</code>-method</a>.
Allow me to demonstrate that:</p>
<pre><span class="Comment"># Attributes of Person include:</span>
<span class="Comment">#</span>
<span class="Comment"># * first_name  string</span>
<span class="Comment"># * name_infix  string</span>
<span class="Comment"># * last_name   string</span>
<span class="Comment"># * male        boolean</span>
<span class="Comment">#</span>
<span class="Keyword">class</span> <span class="Type">Person</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  composed_of <span class="Constant">:name</span>,   <span class="Constant">:mapping</span> =&gt; <span class="Type">Name</span>.members
  composed_of <span class="Constant">:gender</span>, <span class="Constant">:mapping</span> =&gt; <span class="Type">Gender</span>.members
<span class="Keyword">end</span></pre><pre><span class="Keyword">class</span> <span class="Type">Name</span> &lt; <span class="Type">Struct</span>.new(<span class="Constant">:first_name</span>, <span class="Constant">:name_infix</span>, <span class="Constant">:last_name</span>, <span class="Constant">:gender</span>)

  <span class="PreProc">def</span> <span class="Function">to_s</span>
    [ first_name, name_infix, last_name ].select(&amp;<span class="Constant">:present?</span>).join(<span class="rubyStringDelimiter">'</span><span class="String"> </span><span class="rubyStringDelimiter">'</span>)
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">first_name</span>
    <span class="Keyword">super</span>.presence || title
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">title</span>
    <span class="Type">I18n</span>.t(gender.key, <span class="Constant">:scope</span> =&gt; <span class="Constant">:titles</span>)
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre><pre><span class="Keyword">class</span> <span class="Type">Gender</span> &lt; <span class="Type">Struct</span>.new(<span class="Constant">:male</span>)

  <span class="PreProc">def</span> <span class="Function">to_s</span>
    <span class="Type">I18n</span>.t(key, <span class="Constant">:scope</span> =&gt; <span class="Constant">:genders</span>)
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">key</span>
    male ? <span class="Constant">:male</span> : <span class="Constant">:female</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>By defining <code>to_s</code> on these structs you can output their gender or name in views without doing
anything special:</p>
<pre><span class="Special">%</span><span class="Conditional">dl</span><span class="Delimiter">[</span><span class="Identifier">@person</span><span class="Delimiter">]</span>
  <span class="Special">%</span><span class="Conditional">dt</span><span class="Special">=</span> <span class="Type">Person</span>.human_attribute_name(<span class="Constant">:name</span>)
  <span class="Special">%</span><span class="Conditional">dd</span><span class="Special">=</span> <span class="Identifier">@person</span>.name

  <span class="Special">%</span><span class="Conditional">dt</span><span class="Special">=</span> <span class="Type">Person</span>.human_attribute_name(<span class="Constant">:gender</span>)
  <span class="Special">%</span><span class="Conditional">dd</span><span class="Special">=</span> <span class="Identifier">@person</span>.gender</pre>
<p>In this example, <code>Person</code> is actually an aggregate of the entity <code>Person</code> and two value objects,
called <code>Name</code> and <code>Gender</code>. Although all attributes are flattened out in your persistence layer (in
this case, your database table); they do have a deeper <strong>struct</strong>ure in your code. And it&#39;s easier
to test too!</p>

<h3 id="toc_2">Services</h3>

<p>Things that aren&#39;t really a &#39;thing&#39; in the domain you&#39;re designing are usually services. They are
not really part of any entity or value object, but do something with them.</p>

<p>In Rails, these would be
<a href="http://guides.rubyonrails.org/active_record_validations_callbacks.html#observers">observers</a> or
plain Ruby objects lying around. Maybe it&#39;s time to call them what they are and place them in
<code>app&#47;services</code>.</p>

<p>Every Rails developer knows the pattern &quot;Fat Model, Skinny Controller&quot;. This is a pattern to
remember that you shouldn&#39;t put model logic in your controller but in your model. But this pattern
is often taken too far. There are people that give the <code>params</code>-object, or worse, the entire
controller-instance, to the model and do their shit there. This is not right. Use a service for
that.</p>

<p>Pagination and searching are good candidates for a service. But this blog post is on the long side,
so I&#39;ll save an example implementation of that for another time. No post is complete without a
promise to a follow-up that never comes, right?</p>

<h12 id="toc_41943040">Conclusion</h3>

<p>It&#39;s the same as I said during my talk: Rails helps you by keeping accidental complexity at a
minimum. You can use the techniques described in Domain Driven Design to organize essential
complexity and make your application more maintainable. Just be careful not to over-engineer it,
that would defeat the purpose. Always be critical of your own code and continue to ask yourself the
same question: <em>&quot;Does this make my code better?&quot;</em></p>
]]>
      </description>
      <guid>http://iain.nl/domain-driven-design-building-blocks-in-ruby</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Customizing IRB, 2010 edition</title>
      <link>http://iain.nl/customizing-irb-2010-edition</link>
      <pubDate>Sat, 24 Jul 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>TL;DR</strong>: Check out my new <a href="http://github.com/iain/osx_settings/blob/master/.irbrc"><code>.irbrc</code>-file</a>!</p>

<p>Customizing my work environment is a nerdish hobby of mine. I spend far to much time tweaking my
terminal. While I&#39;ll save my terminal customizations for another time, I&#39;ll show you my IRB tweaks
in this post.</p>

<p>There are several tools to improve your IRB, and some of them have been around for ages. But the
arrival of <a href="http://gembundler.com/">Bundler</a> makes it difficult to use them. Bundler creates a
bubble in which you have to specify your dependencies explicitly. Furthermore, with project specific
gemsets, provided by the ever so awesome <a href="http://rvm.beginrescueend.com/">RVM</a>, we need to install
these IRB extensions for every project.</p>

<p>This means that you cannot be sure that extensions like Wirble are available in your new and shiny
Rails console. There is only one way around that: add them to your Gemfile. This is what I usually
add:</p>
<pre>group <span class="Constant">:development</span> <span class="rubyControl">do</span>
  gem <span class="rubyStringDelimiter">"</span><span class="String">wirble</span><span class="rubyStringDelimiter">"</span>
  gem <span class="rubyStringDelimiter">"</span><span class="String">hirb</span><span class="rubyStringDelimiter">"</span>
  gem <span class="rubyStringDelimiter">"</span><span class="String">awesome_print</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:require</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">ap</span><span class="rubyStringDelimiter">"</span>
  gem <span class="rubyStringDelimiter">"</span><span class="String">interactive_editor</span><span class="rubyStringDelimiter">"</span>
<span class="rubyControl">end</span></pre>
<h3 id="toc_0">Extension Loading</h3>

<p>To load the IRB extensions without blowing up in your face when they&#39;re not available, I gently try
to load them, and configure them only when that is successful. <a href="http://github.com/iain/osx_settings/blob/master/.irbrc">You can download my <code>.irbrc</code> on
github</a>. Here is what it looks like:</p>

<figure class="ir_black"><img src="/irb.png" alt="" title="irb" width="737" height="188"></figure>

<p>When you start IRB, it shows a line with the extensions loaded. If it&#39;s gray, it&#39;s not appropriate
(like rails2 in this example), loaded extensions are green and extensions that are not available are
in red.</p>

<h3 id="toc_1">Showing Queries in ActiveRecord 3</h3>

<p>As you can see, the queries done by ActiveRecord are displayed in the same way as they are displayed
in your log files. In Rails 2, you would&#39;ve done this by redirecting the log output to <code>STDOUT</code>. In
Rails 3 you need to subscribe to the &#39;<code>sql.active_record</code>&#39;-notifications.</p>

<p>This could in theory also be done for other Rails 3 compatible ORMs like Mongoid, but I haven&#39;t
looked into that yet.</p>

<h3 id="toc_2">Hirb</h3>

<p><a href="http://tagaholic.me/hirb/">Hirb</a> formats objects into pretty tables, as you can see in the picture
above. It also provides some scrolling possibilities like the command line tools less and more. Very
handy!</p>

<h3 id="toc_3">Wirble</h3>

<p>The first IRB extension anyone uses. <a href="http://pablotron.org/software/wirble/">Wirble</a> provides you
with history and syntax highlighting.</p>

<h3 id="toc_4">Awesome Print</h3>

<p>While Wirble colorizes the output to improve readability, it can get cluttered
really fast, especially when you&#39;re dealing with nested hashes and arrays.
<a href="http://github.com/michaeldv/awesome_print">AwesomePrint</a> helps to untangle your object mess:</p>

<figure class="ir_black"><img src="/awesomeprint.png" alt="" title="awesomeprint" width="278"
height="150"></figure>

<h3 id="toc_5">Print Methods</h3>

<p>The &#39;<code>pm</code>&#39;-extension I found <a href="http://snippets.dzone.com/posts/show/2916">on the intertubes</a> some
time ago, lists the methods and what arguments they take on any given object. You can filter it, by
providing a regex. This is what it looks like:</p>

<figure class="ir_black"><img src="/pm.png" alt="" title="pm" width="324" height="138"></figure>

<p>It&#39;s not a gem, but a snippet pasted directly into my irbrc, so it&#39;s always available.</p>

<h3 id="toc_6">Interactive Editor</h3>

<p>Open vim (or any other editor) from IRB, edit your code, save it, close your editor and the code
gets executed. Open vim again and your code is visible and editable again. Very awesome! <a href="http://github.com/jberkel/interactive_editor">Check it
out</a>!</p>

<h3 id="toc_7">More</h3>

<p>Yeah, there more. There&#39;s
<a href="http://tagaholic.me/2009/07/16/bond-from-irb-with-completion-love.html">bond</a>, which
makes autocompletion better, and <a href="http://utilitybelt.rubyforge.org/">utility belt</a>, and
more. I can&#39;t remember to use them all, so I haven&#39;t included them into my irbrc. They
certainly are cool enough for you to check out! Also, a lot of great tips are <a href="http://stackoverflow.com/questions/123494/whats-your-favourite-irb-trick">here on Stack
Overflow</a>.</p>

<p>If you have any good tips, please share them! Oh, and the other OSX tweaks I use are on
<a href="http://github.com/iain/osx_settings">github</a>.</p>

<p>PS. For those that don&#39;t know how to load this: put the <code>.irbrc</code> file in your home directory and it
will load automatically.</p>
]]>
      </description>
      <guid>http://iain.nl/customizing-irb-2010-edition</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Using Sass with jQuery UI</title>
      <link>http://iain.nl/using-sass-with-jquery-ui</link>
      <pubDate>Sun, 11 Jul 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Want to build a quick website or backend? Want to make it look good, but without adding too much
effort in it? Then this recipe is for you!</p>

<p>The <a href="http://jqueryui.com">jQuery UI framework</a> contains some nice styles and some nice javascript
to accompany it. But the class names you&#39;re ought to be using are awkward. Nobody wants to add
&quot;ui-widget-header&quot; to their classes. We have standards; we want semantical html and css, even if we
don&#39;t want to be doing much styling ourselves.</p>

<p>Editing the css file that jQuery UI gives you is not an option; that would be a hideous mess even
before we get started. Luckily, <a href="http://sass-lang.com">Sass</a> can help us. Sass introduced the
&quot;<code>@extend</code>&quot; method since version 3, which we can (ab)use.</p>

<p>We need to convert the css file jQuery gave us to Sass. I&#39;m a big fan of sass, not scss, so I&#39;ll be
using that:</p>
<pre>sass-convert <span class="Special">--from</span> css <span class="Special">--to</span> sass path/to/jquery-ui<span class="Number">-1</span>.<span class="Number">8</span>.<span class="Number">2</span>.custom.css <span class="Operator">&gt;</span> app/stylesheets/_jquery_ui.sass</pre>
<p>I&#39;ve included an underscore so it won&#39;t be compiled to a real css file when I run my application.
I&#39;ve also configured Sass to load my sass files from <code>app&#47;stylesheets</code>.</p>

<p>Next, create your own sass&#47;scss file and use <code>@extend</code>:</p>

<p>In sass:</p>
<pre><span class="PreProc">@import jquery_ui</span>

<span class="Special">.</span><span class="Type">project-header</span>
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-widget</span>
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-widget-header</span>
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-corner-all</span></pre>
<p>In scss:</p>
<pre><span class="PreProc">@import "jquery_ui";</span>

<span class="Special">.</span><span class="Type">project-header</span> <span class="Function">{</span>
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-widget</span>;
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-widget-header</span>;
  <span class="PreProc">@extend</span> <span class="Special">.</span><span class="Type">ui-corner-all</span>;
<span class="Function">}</span></pre>
<p>Now you just need to add the class &quot;<code>project-header</code>&quot; to the appropriate HTML element, include the
compiled &quot;screen.css&quot; tag in your layout and you&#39;re done!</p>

<p>Be sure to use the javascript too, for nice interactions. The javascript will add classes
dynamically to certain elements. They will still work.</p>

<p>So what really happens? Well, <code>@extend</code> appends your own selector to the jQuery selector you
specified. So the compiled jQuery css would&#39;ve looked like this before:</p>
<pre><span class="Function">.ui-widget-header</span> <span class="Function">{</span>
  <span class="Type">border</span>: <span class="Number">1px</span> <span class="Type">solid</span> <span class="Constant">#aaaaaa</span>;
  <span class="Comment">/* more... */</span>
<span class="Function">}</span></pre>
<p>But after doing our <code>@extend</code>-trick, it will now compile to:</p>
<pre><span class="Function">.ui-widget-header</span><span class="Normal">,</span> <span class="Function">.project-title</span> <span class="Function">{</span>
  <span class="Type">border</span>: <span class="Number">1px</span> <span class="Type">solid</span> <span class="Constant">#aaaaaa</span>;
  <span class="Comment">/* more... */</span>
<span class="Function">}</span></pre>
<p>Sass parsing is incredibly smart. Really smart. The original jQuery css will be changed
automatically. Awesome! And without hardly any effort from my side!</p>

<p>For more awesomeness in styling: Have a look at <a href="http://compass-style.org">compass</a>. It will be
worth your time!</p>
]]>
      </description>
      <guid>http://iain.nl/using-sass-with-jquery-ui</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>About structs</title>
      <link>http://iain.nl/about-structs</link>
      <pubDate>Mon, 28 Jun 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Recently I talked about a <a href="/monkey-patch-of-the-month-attr_initializer">monkey patch called attr_initializer</a>, allowing you to write code like this:</p>
<pre><span class="Keyword">class</span> <span class="Type">FooBar</span>
  attr_initializer <span class="Constant">:foo</span>, <span class="Constant">:bar</span>
  <span class="PreProc">def</span> <span class="Function">to_s</span>
    <span class="rubyStringDelimiter">"</span><span class="String">your </span><span class="rubyInterpolationDelimiter">#{</span>foo<span class="rubyInterpolationDelimiter">}</span><span class="String"> is </span><span class="rubyInterpolationDelimiter">#{</span>bar<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span>

<span class="Type">FooBar</span>.new(<span class="rubyStringDelimiter">'</span><span class="String">foo</span><span class="rubyStringDelimiter">'</span>, <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>)</pre>
<p>But there is a way of doing it without a monkey patch. Use the <a href="http://apidock.com/ruby/Struct">Struct</a>.</p>
<pre><span class="Type">FooBar</span> = <span class="Type">Struct</span>.new(<span class="Constant">:foo</span>, <span class="Constant">:bar</span>) <span class="rubyControl">do</span>
  <span class="PreProc">def</span> <span class="Function">to_s</span>
    <span class="rubyStringDelimiter">"</span><span class="String">your </span><span class="rubyInterpolationDelimiter">#{</span>foo<span class="rubyInterpolationDelimiter">}</span><span class="String"> is </span><span class="rubyInterpolationDelimiter">#{</span>bar<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>
<span class="rubyControl">end</span>

<span class="Type">FooBar</span>.new(<span class="rubyStringDelimiter">'</span><span class="String">foo</span><span class="rubyStringDelimiter">'</span>, <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>)</pre>
<p>Pretty cool.</p>

<h3>Update</h3>

<p>As was pointed out in my comments by <a href="http://rstankov.com/">Radoslav Stankov</a> (which you can&#39;t see anymore, because I switched to Disqus), you can also do this:</p>
<pre><span class="Keyword">class</span> <span class="Type">FooBar</span> &lt; <span class="Type">Struct</span>.new(<span class="Constant">:foo</span>, <span class="Constant">:bar</span>)
  <span class="PreProc">def</span> <span class="Function">to_s</span>
    <span class="rubyStringDelimiter">"</span><span class="String">your </span><span class="rubyInterpolationDelimiter">#{</span>foo<span class="rubyInterpolationDelimiter">}</span><span class="String"> is </span><span class="rubyInterpolationDelimiter">#{</span>bar<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span>

<span class="Type">FooBar</span>.new(<span class="rubyStringDelimiter">'</span><span class="String">foo</span><span class="rubyStringDelimiter">'</span>, <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>)</pre>
<p>I use this one more often, actually.</p>

<p>One final note: the parameters here aren&#39;t stored as instance variables, they can only be accessed through their accessor methods.</p>
]]>
      </description>
      <guid>http://iain.nl/about-structs</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Cheating Performance With A Little Javascript</title>
      <link>http://iain.nl/cheating-performance-with-a-little-javascript</link>
      <pubDate>Thu, 20 May 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>This little trick works with most websites with a menubar. When you have a menu that changes color
pending on which page you are, you can cheat a bit on the perceived performance of loading pages.
And all with just a little bit of Javascript. Intercept the links to change the state to active,
before actually loading the page. The menu will feel much more responsive!</p>

<p>Imagine you add a class to the menu item that is active, like this:</p>
<pre><span class="Keyword">&lt;</span><span class="Conditional">nav</span><span class="Keyword"> </span><span class="Type">id</span><span class="Keyword">=</span><span class="String">"menu"</span><span class="Keyword">&gt;</span>
  <span class="Keyword">&lt;</span><span class="Conditional">ul</span><span class="Keyword">&gt;</span>
    <span class="Keyword">&lt;</span><span class="Conditional">li</span><span class="Keyword">&gt;&lt;</span><span class="Conditional">a</span><span class="Keyword"> </span><span class="Type">href</span><span class="Keyword">=</span><span class="String">"foo.html"</span><span class="Keyword">&gt;</span><span class="Underlined">Foo</span><span class="Identifier">&lt;/</span><span class="Conditional">a</span><span class="Identifier">&gt;&lt;/</span><span class="Conditional">li</span><span class="Identifier">&gt;</span>
    <span class="Keyword">&lt;</span><span class="Conditional">li</span><span class="Keyword"> </span><span class="Type">class</span><span class="Keyword">=</span><span class="String">"active"</span><span class="Keyword">&gt;&lt;</span><span class="Conditional">a</span><span class="Keyword"> </span><span class="Type">href</span><span class="Keyword">=</span><span class="String">"bar.html"</span><span class="Keyword">&gt;</span><span class="Underlined">Bar</span><span class="Identifier">&lt;/</span><span class="Conditional">a</span><span class="Identifier">&gt;&lt;/</span><span class="Conditional">li</span><span class="Identifier">&gt;</span>
    <span class="Keyword">&lt;</span><span class="Conditional">li</span><span class="Keyword">&gt;&lt;</span><span class="Conditional">a</span><span class="Keyword"> </span><span class="Type">href</span><span class="Keyword">=</span><span class="String">"baz.html"</span><span class="Keyword">&gt;</span><span class="Underlined">Baz</span><span class="Identifier">&lt;/</span><span class="Conditional">a</span><span class="Identifier">&gt;&lt;/</span><span class="Conditional">li</span><span class="Identifier">&gt;</span>
  <span class="Identifier">&lt;/</span><span class="Conditional">ul</span><span class="Identifier">&gt;</span>
<span class="Identifier">&lt;/</span><span class="Conditional">nav</span><span class="Identifier">&gt;</span></pre>
<p>Then all you would need to do is something like this with jQuery:</p>
<pre>$(<span class="Function">function</span>() <span class="Function">{</span>
  $(<span class="String">'nav#menu a'</span>).click(<span class="Function">function</span>()<span class="Function">{</span>
    $(<span class="String">'nav#menu li'</span>).removeClass(<span class="String">'active'</span>);
    $(<span class="Identifier">this</span>).blur().parents(<span class="String">'li'</span>).addClass(<span class="String">'active'</span>);
  <span class="Function">}</span>);
<span class="Function">}</span>);</pre>
<p>I&#39;ve added a <code>blur()</code>-command in between, so the dotted lines disappear earlier.</p>

<p>Try it out, you can really notice the difference. It works best when the menu items don&#39;t move, but
only change appearance.</p>

<h3 id="toc_0">Update</h3>

<p>Because I switched to Disqus, some nice comments have gone. <a href="http://twitter.com/sborsje">Stefan
Borsje</a>, of <a href="http://pressdoc.com">Pressdoc</a> fame, replied with this
concern:</p>

<blockquote>
<p>To be honest, I don’t like it very much. It really changes a basic way the web works; you click
on something, the page loads (and optionally shows an activity indicator) and you get to see the
result. With this method you already get see part of the result even before the actual loading fase,
which could easily confuse users by letting them think the page is already done but nothing has
changed.</p>
</blockquote>

<p>I agree that you should be careful applying this technique. But the clicking of the link is done
instantly, so the user would see the page loading immediately, thus he&#47;she wouldn&#39;t think the page
is done. This technique works best if your pages are speedy enough, but can use just a bit more
oomph.</p>
]]>
      </description>
      <guid>http://iain.nl/cheating-performance-with-a-little-javascript</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Helpers Are Code Too!</title>
      <link>http://iain.nl/helpers-are-code-too</link>
      <pubDate>Sat, 15 May 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I think <a href="/bringing-objects-to-views">I&#39;ve talked about this</a> before, and there has been a
<a href="http://railscasts.com/episodes/101-refactoring-out-helper-object">Railscasts episode</a> about it too,
but I want to touch on it again. I know we&#39;re supposed to keep views simple, but that doesn&#39;t mean
that helpers can only contain methods.</p>

<p>Rails gives you a helper module for every controller. The problem with modules is that they don&#39;t
contain state and are usually used to just put a lot of methods in. But this can grow quickly out of
hand when the stuff that you&#39;re building is a little more complex.</p>

<p>Never forget to run tools like <a href="http://wiki.github.com/kevinrutherford/reek/">Reek</a> on your helpers
as well. What do they say? Are your methods too long? Do your methods require too many arguments? Is
the complexity too high? Do your methods have <em>feature envy</em>?</p>

<p>I&#39;ve seen quite a lot of Rails projects and helpers are almost always the forgotten parts of the
application. Every Rails developer knows about the &quot;Skinny Controller, Fat Model&quot;-principle. Better
teams also make skinny models, by using modules and creating macro&#39;s. But helpers are usually ugly.
And they shouldn&#39;t!</p>

<p><strong>Helpers are code too! They want your love and dedication!</strong></p>

<p>There are a couple of ways to keep it clean. Sometimes they are called &quot;Presenter Objects&quot; or
something similar. It doesn&#39;t matter how you call them, and you don&#39;t have to use any complicated
gems or libraries. Regular classes suffice.</p>

<p>Here&#39;s an example of a typical helper:</p>
<pre><span class="Keyword">module</span> <span class="Type">PostsHelper</span>

  <span class="PreProc">def</span> <span class="Function">post_title</span>(post)
    header_class = post.published? ? <span class="rubyStringDelimiter">"</span><span class="String">published</span><span class="rubyStringDelimiter">"</span> : <span class="rubyStringDelimiter">"</span><span class="String">normal</span><span class="rubyStringDelimiter">"</span>
    header = content_tag(<span class="Constant">:h2</span>, post.title, <span class="Constant">:class</span> =&gt; header_class)
    content_tag(<span class="Constant">:div</span>, <span class="Constant">:class</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">post header</span><span class="rubyStringDelimiter">"</span>) <span class="rubyControl">do</span>
      <span class="Conditional">if</span> post.user == current_user
        [ header, edit_post(post), destroy_post(post) ].compact.join(<span class="rubyStringDelimiter">'</span><span class="String"> </span><span class="rubyStringDelimiter">'</span>)
      <span class="Conditional">else</span>
        header
      <span class="Conditional">end</span>
    <span class="rubyControl">end</span>
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">edit_post</span>(post)
    link_to(<span class="rubyStringDelimiter">'</span><span class="String">edit</span><span class="rubyStringDelimiter">'</span>, edit_post_path(post))
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">destroy_post</span>(post)
    link_to(<span class="rubyStringDelimiter">'</span><span class="String">delete</span><span class="rubyStringDelimiter">'</span>, post, <span class="Constant">:method</span> =&gt; <span class="Constant">:delete</span>, <span class="Constant">:confirm</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">are you sure?</span><span class="rubyStringDelimiter">"</span>)
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>You might choose a different route, like putting the <code>if</code>-statement in the view. But that&#39;s beside
the point. The point is that this is what usually happens when you don&#39;t use objects as they are
supposed to be used. Look at the post argument for example. It&#39;s on every frickin&#39; method! That&#39;s
not <abbr title="Don't Repeat Yourself">DRY</abbr>!</p>

<p>And what if you need to extend it? What if you need approve and reject links as well? What if the
destroy link needs to only show when the post has been approved? It&#39;s becoming more and more messy.
Time to refactor!</p>

<p>This is an example of how I would do it:</p>
<pre><span class="Keyword">module</span> <span class="Type">PostsHelper</span>

  <span class="PreProc">def</span> <span class="Function">post_title</span>(post)
    <span class="Type">PostTitle</span>.new(<span class="Constant">self</span>, post).to_html
  <span class="PreProc">end</span>

  <span class="Keyword">class</span> <span class="Type">PostTitle</span>

    attr_initializer <span class="Constant">:template</span>, <span class="Constant">:post</span>
    delegate <span class="Constant">:content_tag</span>, <span class="Constant">:link_to</span>, <span class="Constant">:current_user</span>, <span class="Constant">:to</span> =&gt; <span class="Constant">:template</span>

    <span class="PreProc">def</span> <span class="Function">to_html</span>
      content_tag(<span class="Constant">:div</span>, elements, <span class="Constant">:class</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">post header</span><span class="rubyStringDelimiter">"</span>)
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">elements</span>
      [ header, edit, delete, approve, reject ].compact.join(<span class="rubyStringDelimiter">'</span><span class="String"> </span><span class="rubyStringDelimiter">'</span>)
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">header</span>
      content_tag(<span class="Constant">:h2</span>, post.title, <span class="Constant">:class</span> =&gt; header_class)
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">header_class</span>
      post.published? ? <span class="rubyStringDelimiter">"</span><span class="String">published</span><span class="rubyStringDelimiter">"</span> : <span class="rubyStringDelimiter">"</span><span class="String">normal</span><span class="rubyStringDelimiter">"</span>
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">edit</span>
      link_to(<span class="rubyStringDelimiter">'</span><span class="String">edit</span><span class="rubyStringDelimiter">'</span>, edit_post_path(post)) <span class="Conditional">if</span> my_post?
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">my_post?</span>
      post.user == current_user
    <span class="PreProc">end</span>

    <span class="Comment"># etc... (you get the drift)</span>

  <span class="Keyword">end</span>

<span class="Keyword">end</span></pre>
<p>Nice! Small testable methods! Readable code! Less repetition. <em>Run Reek on that!</em></p>

<p>If you&#39;re wondering what the <code>attr_initializer</code> is, it&#39;s a monkey patch,
that I&#39;ve <a href="/monkey-patch-of-the-month-attr_initializer">described here</a>. The
<a href="http://apidock.com/rails/Module/delegate">delegate-method</a> is something ActiveSupport offers you.
Use it, it&#39;s super effective!</p>

<p>Wait a minute. Did I say &quot;testable&quot;? Yes, I most certainly did! As with any code, this needs to be
tested. But it&#39;s not that hard anymore! If you&#39;re using <a href="http://rspec.info">Rspec</a>, you can use the
<a href="http://rspec.info/rails/writing/helpers.html">helper specs</a> it provides. But you don&#39;t need to!</p>

<p>The <code>PostTitle</code>-class is a regular Ruby class, and so every test framework can test with it without
much effort. You might want to use stubs and mocks for the other helper methods you call. Or
subclass <code>PostTitle</code>, define the used helper methods and use this to subclass in your tests. The
<code>delegate</code> specifies which other helper methods are used.</p>

<p>Remember that what you program is entirely up to you. You, and only you, have to decide when a
simple method is enough, or whether you need to add a class, or something similar. You can also
consider using <a href="http://builder.rubyforge.org/">Builder</a> for some parts, if the HTML generation
becomes too hard.</p>

<p>The main point is that any part of your application needs to receive the same attention to detail.
Don&#39;t hide your dead bodies (of code) in helpers, or anywhere! Be critical everywhere and all the
time! Run Reek regularly. It&#39;s a depressing tool and you don&#39;t need to fix every message every time.
Use it wisely and pay attention. There is <strong>no</strong> excuse for ugly code!</p>

<p>In this example, I would use a partial, but when the view logic increases, you should be thinking
about extracting it.</p>
]]>
      </description>
      <guid>http://iain.nl/helpers-are-code-too</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Conway's Game of Life; or: Writing Perl in Ruby</title>
      <link>http://iain.nl/conways-game-of-life-or-writing-perl-in-ruby</link>
      <pubDate>Fri, 30 Apr 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>We had a programming exercise this week at work. We were set out to write <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&#39;s Game of
Life</a>, using pair programming and TDD. It was
a fun and educational evening. I even did some Scala.</p>

<p>Programmers humor dictates me that from time to time I say things like &quot;In Ruby, that&#39;s only one
line!&quot; or &quot;In Ruby, that would cost me just one minute!&quot;. Putting money where my mouth is, I wrote
the entire application in just one line of Ruby.</p>

<p>So here it is. It looks more like Perl than Ruby. But it works!</p>
<pre><span class="Type">String</span>.class_eval{define_method(<span class="Constant">:to_grid</span>){(<span class="Constant">self</span> =~ <span class="rubyRegexpDelimiter">/</span><span class="Special">\A</span><span class="Special">(</span><span class="Special">\d</span><span class="Special">+</span><span class="Special">)</span><span class="rubyRegexp">x</span><span class="Special">(</span><span class="Special">\d</span><span class="Special">+</span><span class="Special">)</span><span class="Special">\z</span><span class="rubyRegexpDelimiter">/</span> ?
(<span class="Number">0</span>...split(<span class="rubyStringDelimiter">'</span><span class="String">x</span><span class="rubyStringDelimiter">'</span>).last.to_i).map{|<span class="Identifier">_</span>| (<span class="Number">0</span>...split(<span class="rubyStringDelimiter">'</span><span class="String">x</span><span class="rubyStringDelimiter">'</span>).first.to_i).map{|<span class="Identifier">_</span>| rand &gt; <span class="Number">0.5</span> } } :
split(<span class="rubyStringDelimiter">"</span><span class="Special">\n</span><span class="rubyStringDelimiter">"</span>).map{|<span class="Identifier">row</span>| row.split(<span class="rubyRegexpDelimiter">//</span>).map{|<span class="Identifier">cell_string</span>| cell_string == <span class="rubyStringDelimiter">"</span><span class="String">o</span><span class="rubyStringDelimiter">"</span> } }
).tap{|<span class="Identifier">grid</span>| grid.class.class_eval{define_method(<span class="Constant">:next</span>){each{|<span class="Identifier">row</span>|
row.each{|<span class="Identifier">cell</span>| cell.class.class_eval{define_method(<span class="Constant">:next?</span>){|<span class="Identifier">neighbours</span>|
(<span class="Constant">self</span> &amp;&amp; (<span class="Number">2</span>..<span class="Number">3</span>).include?(neighbours.select{|<span class="Identifier">me</span>| me }.size)) ||
(!<span class="Constant">self</span> &amp;&amp; neighbours.select{|<span class="Identifier">me</span>| me }.size == <span class="Number">3</span>)}}}} &amp;&amp;
enum_for(<span class="Constant">:each_with_index</span>).map{|<span class="Identifier">row</span>, <span class="Identifier">row_num</span>| row.enum_for(<span class="Constant">:each_with_index</span>).map{|<span class="Identifier">cell</span>, <span class="Identifier">col_num</span>|
cell.next?([ at(row_num - <span class="Number">1</span>).at(col_num - <span class="Number">1</span>), at(row_num - <span class="Number">1</span>).at(col_num),
at(row_num - <span class="Number">1</span>).at((col_num + <span class="Number">1</span>) % row.size), row.at((col_num + <span class="Number">1</span>) % row.size),
row.at(col_num - <span class="Number">1</span>), at((row_num + <span class="Number">1</span>) % size).at(col_num - <span class="Number">1</span>),
at((row_num + <span class="Number">1</span>) % size).at(col_num), at((row_num + <span class="Number">1</span>) % size).at((col_num + <span class="Number">1</span>) % row.size) ])
} }} &amp;&amp; define_method(<span class="Constant">:to_s</span>){map{|<span class="Identifier">row</span>| row.map{|<span class="Identifier">cell</span>| cell ? <span class="rubyStringDelimiter">"</span><span class="String">o</span><span class="rubyStringDelimiter">"</span> : <span class="rubyStringDelimiter">"</span><span class="String">.</span><span class="rubyStringDelimiter">"</span> }.join }.join(<span class="rubyStringDelimiter">"</span><span class="Special">\n</span><span class="rubyStringDelimiter">"</span>)}}}}}</pre>
<p>I didn&#39;t cheat! No semicolons where harmed during the making of the spaghetti code. I did enter some
newlines in the code shown above to prevent wild scrollbars from appearing.</p>

<p>You can use it like this:</p>
<pre><span class="Comment"># generate a random grid</span>
grid = <span class="rubyStringDelimiter">"</span><span class="String">100x30</span><span class="rubyStringDelimiter">"</span>.to_grid
<span class="Comment"># show the grid:</span>
puts grid.to_s
<span class="Comment"># get the next generation of the grid</span>
new_grid = grid.next
<span class="Comment"># convert a drawn out grid to a grid</span>
new_grid.to_s.to_grid == new_grid <span class="Comment"># returns true</span></pre>
<p>If you want to know how it works, or make an animation of it, <a href="http://gist.github.com/384487">it&#39;s all
here</a>.</p>

<p>This is what it looks like:</p>

<figure class="ir_black"><img src="/game-of-life.png" alt="Conway&#039;s Game of Life" title="Conway&#039;s Game of Life" width="754" height="497"></figure>

<p>It was a fun exercise, but I don&#39;t think I&#39;ll be writing all my code like this in the future :)</p>
]]>
      </description>
      <guid>http://iain.nl/conways-game-of-life-or-writing-perl-in-ruby</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>ViewTranslator, a dynamic dispatcher</title>
      <link>http://iain.nl/viewtranslator-a-dynamic-dispatcher</link>
      <pubDate>Sat, 24 Apr 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I&#39;m a sucker for syntax. So once again, here&#39;s a small experiment. It might not be the most useful snippet out there, but maybe it inspires you to do something awesome. The &#39;Dynamic Dispatcher&#39; is a common pattern in Ruby. Here I&#39;ll demonstrate it to add some syntactic sugar.</p>

<p>In views you can automatically scope translations to the view you&#39;re working in.</p>

<p>So this HAML code (in the <code>users#index</code> view):</p>
<pre><span class="Special">=</span> t(<span class="rubyStringDelimiter">'</span><span class="String">.foo</span><span class="rubyStringDelimiter">'</span>)</pre>
<p>It&#39;s the same as:</p>
<pre><span class="Special">=</span> t(<span class="Constant">:foo</span>, <span class="Constant">:scope</span> =&gt; [<span class="Constant">:users</span>, <span class="Constant">:index</span>])</pre>
<p>I use this technique a lot.</p>

<p>Anyway, we could clean up it even more, by making a dynamic dispatcher. It would look something like this:</p>
<pre><span class="Keyword">module</span> <span class="Type">ViewTranslatorHelper</span>

  <span class="PreProc">def</span> <span class="Function">vt</span>
    <span class="Identifier">@view_translator</span> ||= <span class="Type">ViewTranslator</span>.new(<span class="Constant">self</span>)
  <span class="PreProc">end</span>

  <span class="Keyword">class</span> <span class="Type">ViewTranslator</span> &lt; <span class="Type">ActiveSupport</span>::<span class="Type">BasicObject</span>

    <span class="PreProc">def</span> <span class="Function">initialize</span>(template)
      <span class="Identifier">@template</span> = template
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">method_missing</span>(method, options = {})
      <span class="Type">ViewTranslator</span>.class_eval &lt;&lt;-<span class="rubyStringDelimiter">RUBY</span>
<span class="String">        def </span><span class="rubyInterpolationDelimiter">#{</span>method<span class="rubyInterpolationDelimiter">}</span><span class="String">(options = {})</span>
<span class="String">          @template.t(".</span><span class="rubyInterpolationDelimiter">#{</span>method<span class="rubyInterpolationDelimiter">}</span><span class="String">", options)</span>
<span class="String">        end</span>
<span class="String">      </span><span class="rubyStringDelimiter">RUBY</span>
      __send__(method, options)
    <span class="PreProc">end</span>

  <span class="Keyword">end</span>

<span class="Keyword">end</span></pre>
<p>And now you can write:</p>
<pre><span class="Special">=</span> vt.foo</pre>
<h3 id="toc_0">How does this work?</h3>

<p>The <code>vt</code> method returns <code>ViewTranslator</code> instance. It is cached inside an instance variable. The <code>ViewTranslator</code> object inherits from <code>BasicObject</code> (<code>ActiveSupport</code>&#39;s <code>BasicObject</code> uses Ruby 1.9 if it is on Ruby 1.9, and constructs it&#39;s own when on a lower Ruby version). <code>BasicObject</code> is an object that knows no methods, except methods like <code>__id__</code> and <code>__send__</code>. This makes it ideal for using dynamic dispatchers.</p>

<p>When we define <code>method_missing</code> every single method we call on it will be passed to there. We could call <code>@template.t</code> directly from here, but we don&#39;t. To know why, we must know how <code>method_missing</code> works. When you call a method on an object, it looks to see if the object knows the method. When it doesn&#39;t know it, it looks to it&#39;s superclass and tries again. This happens all the way until it reaches the top of the chain. In Ruby 1.8 that is <code>Object</code>, because every object inherits from <code>Object</code>. Ruby 1.9 goes one step further and goes to <code>BasicObject</code>. If a method is not found anywhere, it will go to the original object you called the method on and it calls <code>method_missing</code>. Since that usually isn&#39;t there, it goes up the superclass chain until it comes to (<code>Basic</code>)<code>Object</code>. There it exists. It will raise the exception we all know and hate: <code>NoMethodError</code>. You can do this yourself too:</p>
<pre>> "any object".method_missing(:to_s)
NoMethodError: undefined method `to_s' for "any object":String
</pre>
<p>You see, even though the method <code>to_s</code> does exist on the string, we stepped halfway in the process of a method call. The error message is a bit confusing, but the we just called a method on the superclass of <code>String</code>. Anyway, by defining <code>method_missing</code> on our own object, it cuts this chain short. To cut it even shorter, I define the method itself, so it doesn&#39;t need to go through this process at all. After it&#39;s defined I call the freshly created method.</p>

<p>Now, to be honest. This is not at all that expensive to use method_missing in this case. The chain is only classes long, so it&#39;s hardly putting a dent in your performance. There are cases were this is <em>very</em> important though. One such case is <code>ActiveRecord</code>. When you call a method on a new <code>ActiveRecord</code>-object for the first time, you reach <code>method_missing</code>. It needs to look at the database to find out if it is an attribute. Looking inside the database is very expensive, so <code>method_missing</code> creates methods for all attributes. If the attribute exists, it will be called, and it&#39;ll be a normal method call from then on.</p>

<p>Thanks for reading. If you found it informative: I love feedback ;)</p>
]]>
      </description>
      <guid>http://iain.nl/viewtranslator-a-dynamic-dispatcher</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Qu'est-ce que c'est Rubyesque?</title>
      <link>http://iain.nl/quest-ce-que-cest-rubyesque</link>
      <pubDate>Mon, 12 Apr 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>This is a translation of <a href="http://blog.finalist.com/2010/04/12/quest-ce-que-cest-rubyesque/">the post I originally wrote down in
Dutch</a> for my company.</p>

<p>I recently gave a presentation at my company Finalist IT Group about the philosophy behind Ruby.
Code written with this philosophy in mind is called &#39;Rubyesque&#39;. It&#39;s not hard science, so we had
plenty ingredients for a discussion.</p>

<p>The reason behind the presentation was because we&#39;re in need of more Ruby developers and looked
inside our own company for Java developers that want to learn Ruby. Because Java and the philosophy
behind it are so radically different from Ruby, we organized a discussion to explore those
differences.</p>

<h3 id="toc_0">About programming and the &#39;flow&#39;</h3>

<p>The Rubyesque mindset is all about opinions. Opinions tend to vary from person to person. By reading
a lot of blogs and code I do see some sort of consensus. This opinion is not always explicitly
mentioned, so I don&#39;t pretend to speak in absolute truths or be complete.</p>

<p>Programming is usually compared with other professions to give an idea what it&#39;s like to do it. Ruby
programmers tend to compare programming with craftsmanship. I even go one step further. I think
programming Ruby is a form of art of playing an instrument. Programming is a creative process.
You&#39;re programming to express meaning and intent. The only way to achieve this, is if you know your
instrument so intensely that it&#39;s not compromising you&#39;re ability to express yourself.</p>

<p>Every programming language has its own style. You can call it its &#39;flow&#39;.
It&#39;s wise to go with the flow. It&#39;s easier to use the language as it&#39;s
intended to be used than to go against it. For example, don&#39;t try to force
<a href="http://en.wikipedia.org/wiki/Class-based_programming">inheritance</a> in a language that is intended
to be <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype based</a>. Program according
to the flow and other programmers can understand and maintain your code better.</p>

<h3 id="toc_1">About Ruby</h3>

<p>Everything in Ruby is aimed towards making the programmer happy. A happy programmer is better
motivated to deliver great code and will feel responsible to do so. And better code makes everyone
happy.</p>

<p>It&#39;s the machine that is supposed to do the heavy lifting, not the programmer. This means that Ruby
isn&#39;t particularly fast, but since machine power is cheaper than man power, it&#39;s not that big of a
deal.</p>

<p>Ruby has a couple of traits that make it a joy to work with:</p>

<ul>
<li>Dynamic and open to bend it to your liking</li>
<li>Few rules, so easy to learn</li>
<li>There are &#39;shortcuts&#39; for common tasks</li>
<li>Many ways to reuse code, such as mixins</li>
<li>Optional punctuation to improve readability</li>
<li>Methods like <a href="http://www.rubyist.net/%7Eslagell/ruby/accessors.html">attr_accessor</a> to become more <a href="http://en.wikipedia.org/wiki/DRY">DRY</a></li>
</ul>

<h3 id="toc_2">Dynamic</h3>

<p>In a dynamic language it&#39;s not important to know which type of object you&#39;re dealing
with, but it&#39;s more important to know what it can do for you. This is called <a href="http://en.wikipedia.org/wiki/Duck_typing">duck
typing</a>. This isn&#39;t only handy in making mock object, but
also means that you don&#39;t have to abuse inheritance to comply to some method you&#39;d like to call.</p>

<p>A nice example is the Rack specification. The header object you&#39;re supposed to return needs to have
the method <code>each</code>. It doesn&#39;t say that it needs to be a hash. You could use a hash, but if it makes
more in your sense to have some other object, it&#39;s fine. You don&#39;t have to inherit from hash, just
to implement the <code>each</code> method.</p>

<p>The <em>flow</em> in Ruby is not to perform any check of the objects. If you&#39;re explicitly want an integer,
just call <code>to_i</code> inside the method. Any code that checks the type is usually considered to be
distracting from the real meaning of the code. It&#39;s the programmer that uses the gem&#47;library
responsibility to use the right objects, and not the responsibility of the gem-maker. The naming of
methods and variables need to be obvious enough, so that it shouldn&#39;t be a guessing game.</p>

<h3 id="toc_3">Open</h3>

<p>In Ruby, nothing is final. This allows for the ability to add and change anything
in any object, including core classes. This is called Monkey Patching or <a href="http://en.wikipedia.org/wiki/Duck_punching">duck
punching</a>. This results in even nicer and more readable
code, like:</p>
<pre><span class="Number">15</span>.minutes.ago</pre>
<p>Nobody needs to explain this. Nobody needs to look up any documents to understand what is going on
here. Monkey patching can improve the readability of the code immensely.</p>

<p>I understand that this technique may be considered extreme by some people. It doesn&#39;t comply to the
strict rules that govern most other languages. Still, these kinds of techniques are very handy and
addicting.</p>

<p>Monkey patching is dangerous. It&#39;s your own responsibility to use it responsible. Use tests to
ensure that you don&#39;t break anything unintentionally.</p>

<h3 id="toc_4">Punctuation</h3>

<p>Some of Ruby&#39;s punctuation is optional. Ruby programmers love to leave them out. It&#39;s mostly a
matter of taste. Readability is key here.</p>

<p>Rubyists rather write this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span>
  belongs_to <span class="Constant">:author</span>, <span class="Constant">:dependent</span> =&gt; <span class="Constant">:destroy</span>
<span class="Keyword">end</span></pre>
<p>Than the same code with all punctuation visible:</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span>
  belongs_to(<span class="Constant">:author</span>, {<span class="Constant">:dependent</span> =&gt; <span class="Constant">:destroy</span>})
<span class="Keyword">end</span></pre>
<p>It&#39;s not important that <tt>{:dependent =&gt; :destroy}</tt> is a hash. Nor is it important that
<code>belong_to</code> is a method, and that it takes two arguments. It&#39;s much more important that the post
belongs to an author and that the post will be destroyed when the author is being destroyed.</p>

<p>By not using all the possible punctuation, it becomes easier for our brains to focus on <em>what</em> is
actually written, rather that <em>which objects</em> might be used to express it.</p>

<h3 id="toc_5">Few rules, many shortcuts</h3>

<p>There are only a few genuine language constructs. There are just three elements in the language that
have any real meaning. Those are objects, methods and blocks&#47;closures. The only way in which classes
and modules are special is by their implementation, but they are still regular objects. There are
just a few other constructs, most notably <code>if</code>, <code>while</code> and the logic operators like <code>&amp;&amp;</code> and <code>||</code>.</p>

<p>The rest of the keywords you see are just shortcuts, you can type to perform common tasks. Like
defining a class:</p>
<pre><span class="Keyword">class</span> <span class="Type">Car</span> &lt; <span class="Type">Vehicle</span>
  <span class="Comment"># ...</span>
<span class="Keyword">end</span></pre>
<p>The Ruby interpreter reads this as:</p>
<pre><span class="Type">Car</span> = <span class="Type">Class</span>.new(<span class="Type">Vehicle</span>) <span class="rubyControl">do</span>
  <span class="Comment"># ...</span>
<span class="rubyControl">end</span></pre>
<p>Defining a class is actually just a method called on an object. The first argument is another object
(the class to inherit from) and the second argument is a block. You can write it like this if you
want to and play with it too, like dynamically making many different classes.</p>

<p>Some other examples:</p>
<pre>counter += <span class="Number">1</span>           <span class="Comment"># this is a shortcut</span>
counter = counter + <span class="Number">1</span>  <span class="Comment"># without the shortcut, but also without punctuation</span>
counter = counter.+(<span class="Number">1</span>) <span class="Comment"># without the shortcut and with all punctuation (yes, + is just a method)</span></pre><pre><span class="Identifier">@user</span> ||= <span class="Type">User</span>.new        <span class="Comment"># this is called a 'teapot'-operator or 'or-or-equals'</span>
<span class="Identifier">@user</span> = <span class="Identifier">@user</span> || <span class="Type">User</span>.new <span class="Comment"># assign @user to @user if it exists, otherwise create a new user</span></pre><pre><span class="rubyControl">exit</span> <span class="Conditional">unless</span> busy <span class="rubyControl">or</span> cancelled  <span class="Comment"># 'unless' is a shortcut for 'if !()'</span>
<span class="rubyControl">exit</span> <span class="Conditional">if</span> !(busy <span class="rubyControl">or</span> cancelled)   <span class="Comment"># 'if' at the end of a sentence is also a shortcut</span>
<span class="Conditional">if</span> !(busy <span class="rubyControl">or</span> cancelled)        <span class="Comment"># for a regular if</span>
  <span class="rubyControl">exit</span>
<span class="Conditional">end</span></pre>
<p>There are many more shortcuts. But why? Why are there so many ways to do the same thing? It&#39;s not
just readability, but also the ease in which you can translate the ideas in your head to code.</p>

<p>The smaller the difference between your thoughts and your code, the easier it is to program. Ruby
gives you full freedom to express yourself how you feel fit. That doesn&#39;t mean it always works out.
If you have an unclear image of the problem you&#39;re trying to solve, the code you write will be
unclear too. Nothing stops you to write bad code. Ruby doesn&#39;t force you in any way. These things
cut both ways.</p>

<h3 id="toc_6">Exposing intention</h3>

<p>Code needs to expose its intent. Ruby code is Rubyesque if it uses the above mentioned techniques to
expose its intent. Because Ruby has such clean syntax, most DSLs (Domain Specific Languages) will be
written in Ruby. These kinds of DSLs are called internal.</p>

<p>The naming of variables and methods is extremely important. The meaning of the code must be clear
the first time you read it.</p>

<p>A fantastic example is <a href="http://rspec.info">Rspec</a>, my favorite test framework.</p>
<pre>describe <span class="Type">Post</span> <span class="rubyControl">do</span>

  context <span class="rubyStringDelimiter">"</span><span class="String">when it's not approved</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
    subject { <span class="Type">Post</span>.new(<span class="Constant">:approved</span> =&gt; <span class="Constant">false</span>) }
    it { should_not be_publishable }
  <span class="rubyControl">end</span>

  context <span class="rubyStringDelimiter">"</span><span class="String">when it's approved</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
    subject { <span class="Type">Post</span>.new(<span class="Constant">:approved</span> =&gt; <span class="Constant">true</span>) }
    it { should be_publishable }
  <span class="rubyControl">end</span>

<span class="rubyControl">end</span></pre>
<p>The entire Ruby bag of tricks is being used to make it as natural as possible to write down your
specifications. This example doesn&#39;t like like regular Ruby code, but it still is. It&#39;s nothing more
than objects, methods and blocks.</p>

<p>This is very Rubyesque. There is almost no distraction from the meaning of the code. I can plainly
read if my code still does what my customer wants and I can run the specs to see if my code does
what I specified it to do. And even nicer: it&#39;s incredibly easy! Rspec makes Test Driven Development
very easy.</p>

<p>If you&#39;re interested in the code to implement this example, take a look at <a href="http://gist.github.com/362030">this
gist</a>.</p>

<h3 id="toc_7">Succinct and Concise</h3>

<p>Rubyesque code is succinct. That doesn&#39;t just mean short lines (I try to limit myself to
about 80 or 100 characters per line), but also about short methods. The code smell detector
<a href="http://wiki.github.com/kevinrutherford/reek/">Reek</a> will raise a warning if your method is longer
than 6 lines. Does this means you are not allowed to write longer methods? Of course not. Is it a
good idea? No.</p>

<p>People are better at understanding short sentences. And it&#39;s the people that need to understand the
code and maintain. And we&#39;re back to the philosophy behind Ruby. It&#39;s meant to be understandable for
people. It&#39;s less important if the computer needs to do some extra work.</p>

<h3 id="toc_8">Conclusion</h3>

<p>Ruby is a free language. You can bend the rules. The goal is to make you happy. Ruby was made to
make you happy, to close the gap between human and computer language. Try to do that in the code you
write too, it works!</p>

<p>I found that most people coming from languages like Java or PHP find Ruby a weird or magical
language. That is only the appearance. Ruby is very easy to learn. It has few rules. Ruby
programmers don&#39;t code using rigid rules and dogmas, but experiment solving the same problem in
different ways.</p>

<p>I hope you got some idea of what it means to program Rubyesque. I advise everybody to look at the
different languages and their philosophies. See what philosophy suits you. If the Ruby philosophy
suits you and you have the discipline needed to write Ruby, give it a try! Ruby transformed the way
I feel about my job and never regretted learning it one bit.</p>
]]>
      </description>
      <guid>http://iain.nl/quest-ce-que-cest-rubyesque</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Monkey Patch of the Month: attr_initializer</title>
      <link>http://iain.nl/monkey-patch-of-the-month-attr_initializer</link>
      <pubDate>Mon, 12 Apr 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>So, about one month ago, I <a href="/monkey-patch-of-the-month-group_by">promised</a> to share some useful
monkey patches every month. Here is the second one. Your own monkey patches are still more than
welcome!</p>

<p>I often find myself writing code like this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Foo</span>
  <span class="Statement">attr_reader</span> <span class="Constant">:bar</span>, <span class="Constant">:baz</span>
  <span class="PreProc">def</span> <span class="Function">initialize</span>(bar, baz)
    <span class="Identifier">@bar</span>, <span class="Identifier">@baz</span> = bar, baz
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>This can be very annoying to maintain. The variable names are repeated four times, within three lines of code!</p>

<p>Ideally, I&#39;d want to write something like this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Foo</span>
  attr_initializer <span class="Constant">:bar</span>, <span class="Constant">:baz</span>
<span class="Keyword">end</span></pre>
<p>Much better, if you ask me. Here is one example of how to do this.</p>
<pre><span class="Keyword">class</span> <span class="Type">Class</span>
  <span class="PreProc">def</span> <span class="Function">attr_initializer</span>(*attributes)
    <span class="Statement">attr_reader</span> *attributes
    <span class="Statement">class_eval</span> &lt;&lt;-<span class="rubyStringDelimiter">RUBY</span>
<span class="String">      def initialize(</span><span class="rubyInterpolationDelimiter">#{</span>attributes.join(<span class="rubyStringDelimiter">'</span><span class="String">, </span><span class="rubyStringDelimiter">'</span>)<span class="rubyInterpolationDelimiter">}</span><span class="String">)</span>
<span class="String">        </span><span class="rubyInterpolationDelimiter">#{</span>attributes.map{ |<span class="Identifier">attribute</span>| <span class="rubyStringDelimiter">"</span><span class="String">@</span><span class="rubyInterpolationDelimiter">#{</span>attribute<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span> }.join(<span class="rubyStringDelimiter">'</span><span class="String">, </span><span class="rubyStringDelimiter">'</span>)<span class="rubyInterpolationDelimiter">}</span><span class="String"> = </span><span class="rubyInterpolationDelimiter">#{</span>attributes.join(<span class="rubyStringDelimiter">'</span><span class="String">, </span><span class="rubyStringDelimiter">'</span>)<span class="rubyInterpolationDelimiter">}</span>
<span class="String">      end</span>
<span class="String">    </span><span class="rubyStringDelimiter">RUBY</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>No piece of code is complete without tests, so this is it:</p>
<pre><span class="Keyword">class</span> <span class="Type">AttrInitializerTests</span> &lt; <span class="Type">Test</span>::<span class="Type">Unit</span>::<span class="Type">TestCase</span>

  <span class="PreProc">def</span> <span class="Function">test_attr_initializer</span>
    klass = <span class="Type">Class</span>.new <span class="rubyControl">do</span>
      attr_initializer <span class="Constant">:foo</span>, <span class="Constant">:bar</span>
    <span class="rubyControl">end</span>
    object = klass.new(<span class="Number">1</span>, <span class="rubyStringDelimiter">'</span><span class="String">b</span><span class="rubyStringDelimiter">'</span>)
    assert_equal <span class="Number">1</span>, object.foo
    assert_equal <span class="rubyStringDelimiter">'</span><span class="String">b</span><span class="rubyStringDelimiter">'</span>, object.bar
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/monkey-patch-of-the-month-attr_initializer</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Odd Ruby Methods</title>
      <link>http://iain.nl/odd-ruby-methods</link>
      <pubDate>Tue, 30 Mar 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I recently encountered some methods I didn&#39;t know about.</p>

<h3 id="toc_0">~</h3>

<p>The tilde method (<code>~</code>) is used by <a href="http://sequel.rubyforge.org/">Sequel</a> and you can use it like this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span>
  <span class="PreProc">def</span> <span class="Function">~</span>
    <span class="Number">11</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span>

post = <span class="Type">Post</span>.new
~post <span class="Comment"># =&gt; 11</span></pre>
<p>That&#39;s right: you call this method by placing the tilde <strong>before</strong> the object.</p>

<p>In Sequel it is used to perform NOT queries, by defining the tilde on Symbol:</p>
<pre><span class="Type">Post</span>.where(~<span class="Constant">:deleted_at</span> =&gt; <span class="Constant">nil</span>)
<span class="Comment"># =&gt; SELECT * FROM posts WHERE deleted_at IS NOT NULL</span></pre>
<h3 id="toc_1">-@</h3>

<p>The minus-at (<code>-@</code>) method works just about the same as the tilde method. It is the method called
when a minus-sign is placed <strong>before</strong> the object. In effect, this means that Fixnum is
implemented somewhere along the lines of this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Fixnum</span>
  <span class="PreProc">def</span> <span class="Function">-@</span>
    <span class="Constant">self</span> * <span class="Number">-1</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span>

num = <span class="Number">10</span>
negative = -num <span class="Comment"># =&gt; -10</span></pre>
<p>I found this one browsing through the source of the
<a href="http://github.com/rails/rails/blob/master/activesupport/lib/active_suppor%0At/duration.rb#L34-36"><code>ActiveSupport::Duration</code></a> class (you know, the one you get when you do <code>1.day</code>). I guess it makes
sense.</p>

<p>Be careful with chaining methods though:</p>
<pre>ruby-1.9.1-p378 > num = 5
 => 5
ruby-1.9.1-p378 > -num.to_s
NoMethodError: undefined method `-@' for "5":String
  from (irb):5
  from /Users/iain/.rvm/rubies/ruby-1.9.1-p378/bin/irb:17:in `<main>'
</pre>
<p>This also applies to the tilde method.</p>

<h3 id="toc_2">So?</h3>

<p>I don&#39;t know. Enrich your DSLs and APIs, if it makes any sense to do it.</p>
]]>
      </description>
      <guid>http://iain.nl/odd-ruby-methods</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Monkey Patch of the Month: group_by</title>
      <link>http://iain.nl/monkey-patch-of-the-month-group_by</link>
      <pubDate>Fri, 19 Mar 2010 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>A while back, I talked about <a href="/3-times-activesupport-3">new additions to ActiveSupport</a>. And now, I have a confession to make: I like monkey patches! At least, as long as they&#39;re short and self-explanatory.</p>

<p>I got a few of them lying around, so I am going to post one every month. I also welcome your favorite monkey patch, which you can <a href="mailto:monkey@iain.nl">email me</a>.</p>

<p>So, the first one: <strong>group_by</strong>. This method groups arrays of objects by the result of the block provided and puts the result into a hash.
<pre class="ir_black"><font color="#96cbfe">class</font>&nbsp;<font color="#ffffb6">Array</font>
&nbsp;&nbsp;<font color="#7c7c7c"># Turns an array into a hash, using the results of the block as keys for the</font>
&nbsp;&nbsp;<font color="#7c7c7c"># hash.</font>
&nbsp;&nbsp;<font color="#7c7c7c">#</font>
&nbsp;&nbsp;<font color="#7c7c7c">#&nbsp;&nbsp; [1, 2, 3, 4].group_by(&amp;:odd?)</font>
&nbsp;&nbsp;<font color="#7c7c7c">#&nbsp;&nbsp; # =&gt; {true=&gt;[1, 3], false=&gt;[2, 4]}</font>
&nbsp;&nbsp;<font color="#7c7c7c">#</font>
&nbsp;&nbsp;<font color="#7c7c7c">#&nbsp;&nbsp; [&quot;One&quot;, &quot;Two&quot;, &quot;three&quot;].group_by {|i| i[0,1].upcase }</font>
&nbsp;&nbsp;<font color="#7c7c7c">#&nbsp;&nbsp; # =&gt; {&quot;T&quot;=&gt;[&quot;Two&quot;, &quot;three&quot;], &quot;O&quot;=&gt;[&quot;One&quot;]}</font>
&nbsp;&nbsp;<font color="#96cbfe">def</font>&nbsp;<font color="#ffd2a7">group_by</font>
&nbsp;&nbsp;&nbsp;&nbsp;hash = <font color="#ffffb6">Hash</font>.new { |<font color="#c6c5fe">hash</font>, <font color="#c6c5fe">key</font>|&nbsp;hash[key] = []&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;each { |<font color="#c6c5fe">item</font>|&nbsp;hash[<font color="#96cbfe">yield</font>(item)] &lt;&lt; item }
&nbsp;&nbsp;&nbsp;&nbsp;hash
&nbsp;&nbsp;<font color="#96cbfe">end</font>
<font color="#96cbfe">end</font></pre></p>

<p>No piece of code is complete without tests, so this is it:</p>

<pre class="ir_black"><font color="#96cbfe">class</font>&nbsp;<font color="#ffffb6">ArrayExtGroupingTests</font>&nbsp;&lt; <font color="#ffffb6">Test</font>::<font color="#ffffb6">Unit</font>::<font color="#ffffb6">TestCase</font>

&nbsp;&nbsp;<font color="#96cbfe">def</font>&nbsp;<font color="#ffd2a7">test_group_by</font>
&nbsp;&nbsp;&nbsp;&nbsp;assert_equal {<font color="#99cc99">true</font>=&gt;[<font color="#ff73fd">1</font>, <font color="#ff73fd">3</font>], <font color="#99cc99">false</font>=&gt;[<font color="#ff73fd">2</font>, <font color="#ff73fd">4</font>]}, [<font color="#ff73fd">1</font>, <font color="#ff73fd">2</font>, <font color="#ff73fd">3</font>, <font color="#ff73fd">4</font>].group_by(&amp;<font color="#99cc99">:odd?</font>)
&nbsp;&nbsp;&nbsp;&nbsp;assert_equal {<font color="#336633">&quot;</font><font color="#a8ff60">T</font><font color="#336633">&quot;</font>=&gt;[<font color="#336633">&quot;</font><font color="#a8ff60">Two</font><font color="#336633">&quot;</font>, <font color="#336633">&quot;</font><font color="#a8ff60">three</font><font color="#336633">&quot;</font>], <font color="#336633">&quot;</font><font color="#a8ff60">O</font><font color="#336633">&quot;</font>=&gt;[<font color="#336633">&quot;</font><font color="#a8ff60">One</font><font color="#336633">&quot;</font>]}, [<font color="#336633">&quot;</font><font color="#a8ff60">One</font><font color="#336633">&quot;</font>, <font color="#336633">&quot;</font><font color="#a8ff60">Two</font><font color="#336633">&quot;</font>, <font color="#336633">&quot;</font><font color="#a8ff60">three</font><font color="#336633">&quot;</font>].group_by {|<font color="#c6c5fe">i</font>|&nbsp;i[<font color="#ff73fd">0</font>,<font color="#ff73fd">1</font>].upcase }
&nbsp;&nbsp;<font color="#96cbfe">end</font>

<font color="#96cbfe">end</font></pre>

<h3 id="toc_0">Update</h3>

<p>Silly me, this one is <a href="http://apidock.com/ruby/Enumerable/group_by">already in Ruby itself</a>. Anyway, this is how it works under the cover...</p>
]]>
      </description>
      <guid>http://iain.nl/monkey-patch-of-the-month-group_by</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Going crazy with to_proc</title>
      <link>http://iain.nl/going-crazy-with-to_proc</link>
      <pubDate>Fri, 05 Feb 2010 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>You all know <code>Symbol#to_proc</code>, right? It allows you to write this:</p>
<pre><span class="Comment"># Without Symbol#to_proc</span>
[<span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>].map { |<span class="Identifier">it</span>| it.to_s }
[<span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>].inject { |<span class="Identifier">memo</span>, <span class="Identifier">it</span>| memo * it }

<span class="Comment"># With Symbol#to_proc</span>
[<span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>].map(&amp;<span class="Constant">:to_s</span>)
[<span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>].inject(&amp;<span class="Constant">:*</span>)</pre>
<p>It has been in Rails as long as I can remember, and is in Ruby 1.8.7 and 1.9.x. I love it to death
and I use it everywhere I can.</p>

<p>It is actually quite simple, and you can implement it yourself:</p>
<pre><span class="Keyword">class</span> <span class="Type">Symbol</span>
  <span class="PreProc">def</span> <span class="Function">to_proc</span>
    <span class="Type">Proc</span>.new { |<span class="Identifier">obj</span>, *<span class="Identifier">args</span>| obj.send(<span class="Constant">self</span>, *args) }
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>It works because when you prepend an ampersand (&amp;) to any Ruby object, it calls <code>#to_proc</code> to
get a proc to use as block for the method.</p>

<p>What I always regretted though was not being to pass any arguments, so I hacked and monkeypatched a
bit, and got:</p>
<pre><span class="Keyword">class</span> <span class="Type">Symbol</span>

  <span class="PreProc">def</span> <span class="Function">with</span>(*args, &amp;block)
    <span class="Identifier">@proc_arguments</span> = { <span class="Constant">:args</span> =&gt; args, <span class="Constant">:block</span> =&gt; block }
    <span class="Constant">self</span>
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">to_proc</span>
    <span class="Identifier">@proc_arguments</span> ||= {}
    args = <span class="Identifier">@proc_arguments</span>[<span class="Constant">:args</span>] || []
    block = <span class="Identifier">@proc_arguments</span>[<span class="Constant">:block</span>]
    <span class="Identifier">@proc_arguments</span> = <span class="Constant">nil</span>
    <span class="Type">Proc</span>.new { |<span class="Identifier">obj</span>, *<span class="Identifier">other</span>| obj.send(<span class="Constant">self</span>, *(other + args), &amp;block) }
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>So you can now write:</p>
<pre>some_dates.map(&amp;<span class="Constant">:strftime</span>.with(<span class="rubyStringDelimiter">"</span><span class="String">%d-%M-%Y</span><span class="rubyStringDelimiter">"</span>))</pre>
<p>Not that this is any shorter than just creating the darn block in the first place. But hey, it&#39;s a
good exercise in metaprogramming and show of more of Ruby&#39;s awesome flexibility.</p>

<p>After this I remembered something similar that annoyed me before. It&#39;s that Rails helper methods are
just a bag of methods available to, because they are mixed in your template. So if you have an array
of numbers that you want to format as currency, you&#39;d have to do:</p>
<pre><span class="PreProc">&lt;%=</span> <span class="Identifier">@prices</span>.map { |<span class="Identifier">price</span>| number_to_currency(price) }.to_sentence <span class="PreProc">%&gt;</span></pre>
<p>What if I could apply some <code>to_proc</code>-love to that too? All these helper methods cannot be added to
strings, fixnums, and the likes; that would clutter <em>way</em> to much. Rather, it might by a nice idea
to use procs that understands helper methods. Here is what I created:</p>
<pre><span class="Keyword">module</span> <span class="Type">ProcProxyHelper</span>

  <span class="PreProc">def</span> <span class="Function">it</span>(position = <span class="Number">1</span>)
    <span class="Type">ProcProxy</span>.new(<span class="Constant">self</span>, position)
  <span class="PreProc">end</span>

  <span class="Keyword">class</span> <span class="Type">ProcProxy</span>

    instance_methods.each { |<span class="Identifier">m</span>| undef_method(m) <span class="Conditional">unless</span> m.to_s =~ <span class="rubyRegexpDelimiter">/</span><span class="Special">^</span><span class="rubyRegexp">__</span><span class="Special">|</span><span class="rubyRegexp">respond_to</span><span class="Special">\?</span><span class="Special">|</span><span class="rubyRegexp">method_missing</span><span class="rubyRegexpDelimiter">/</span> }

    <span class="PreProc">def</span> <span class="Function">initialize</span>(object, position = <span class="Number">1</span>)
      <span class="Identifier">@object</span>, <span class="Identifier">@position</span> = object, position
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">to_proc</span>
      <span class="Statement">raise</span> <span class="rubyStringDelimiter">"</span><span class="String">Please specify a method to be called on the object</span><span class="rubyStringDelimiter">"</span> <span class="Conditional">unless</span> <span class="Identifier">@delegation</span>
      <span class="Type">Proc</span>.new { |*<span class="Identifier">values</span>| <span class="Identifier">@object</span>.__send__(*<span class="Identifier">@delegation</span>[<span class="Constant">:args</span>].dup.insert(<span class="Identifier">@position</span>, *values), &amp;<span class="Identifier">@delegation</span>[<span class="Constant">:block</span>]) }
    <span class="PreProc">end</span>

    <span class="PreProc">def</span> <span class="Function">method_missing</span>(*args, &amp;block)
      <span class="Identifier">@delegation</span> = { <span class="Constant">:args</span> =&gt; args, <span class="Constant">:block</span> =&gt; block }
      <span class="Constant">self</span>
    <span class="PreProc">end</span>

  <span class="Keyword">end</span>

<span class="Keyword">end</span></pre>
<p>I used a clean blank class (in Ruby 1.9, you&#39;d want to inherit it from <code>BasicObject</code>), in which I
will provide the proper <code>proc</code>-object. I play around with the argument list a bit, handling multiple
arguments and blocks too. You can now use this syntax:</p>
<pre><span class="PreProc">&lt;%=</span> <span class="Identifier">@prices</span>.map(&amp;it.number_to_currency).to_sentence <span class="PreProc">%&gt;</span></pre>
<p>That is a lot sexier if you as me. And you can use it in any object, not just inside views. And lets
add some extra arguments and some <code>Enumerator</code>-love too:</p>
<pre><span class="Keyword">class</span> <span class="Type">SomeClass</span>
  <span class="PreProc">include</span> <span class="Type">ProcProxyHelper</span>

  <span class="PreProc">def</span> <span class="Function">initialize</span>(name, list)
    <span class="Identifier">@name</span>, <span class="Identifier">@list</span> = name, list
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">apply</span>(value, index, seperator)
    <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span><span class="Identifier">@name</span><span class="rubyInterpolationDelimiter">}</span><span class="String">, </span><span class="rubyInterpolationDelimiter">#{</span>index<span class="rubyInterpolationDelimiter">}</span><span class="String"> </span><span class="rubyInterpolationDelimiter">#{</span>separator<span class="rubyInterpolationDelimiter">}</span><span class="String"> </span><span class="rubyInterpolationDelimiter">#{</span>value<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">applied_list</span>
    <span class="Identifier">@list</span>.map.with_index(&amp;it.apply(<span class="rubyStringDelimiter">"</span><span class="String">:</span><span class="rubyStringDelimiter">"</span>))
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>In case you are wondering, the position you can specify is to tell where the arguments need to go.
Position 0 is the method name, so you shouldn&#39;t use that, but any other value is okay. An example
might be that you cant to wrap an array of texts into span-tags:</p>
<pre><span class="PreProc">&lt;%=</span> some_texts.map(&amp;it(<span class="Number">2</span>).content_tag(<span class="Constant">:span</span>, <span class="Constant">:class</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">foo</span><span class="rubyStringDelimiter">"</span>)).to_sentence <span class="PreProc">%&gt;</span></pre>
<p>So there you have it. I&#39;m probably solving a problem that doesn&#39;t exist. It is however a nice
example of the awesome power of Ruby. I hope you&#39;ve enjoyed this little demonstration of the
possible uses of <code>to_proc</code>.</p>
]]>
      </description>
      <guid>http://iain.nl/going-crazy-with-to_proc</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>3 times ActiveSupport 3</title>
      <link>http://iain.nl/3-times-activesupport-3</link>
      <pubDate>Wed, 03 Feb 2010 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Rails 3 is coming. All the big changes are spoken of elsewhere, so I&#39;m going to mention some small changes. Here are 3 random new methods added to ActiveSupport:</p>

<h3 id="toc_0">presence</h3>

<p>First up is <code>Object#presence</code> which is a shortcut for <code>Object#present? &amp;&amp; Object</code>. It is a bit of a sanitizer. Empty strings and other blank values will return <code>nil</code> and any other value will return itself. Use this one and your code might be a tad cleaner.</p>
<pre><span class="rubyStringDelimiter">""</span>.presence <span class="Comment"># =&gt; nil</span>
<span class="rubyStringDelimiter">"</span><span class="String">foo</span><span class="rubyStringDelimiter">"</span>.presence <span class="Comment">#=&gt; "foo"</span>

<span class="Comment"># without presence:</span>
<span class="Conditional">if</span> params[<span class="Constant">:foo</span>].present? &amp;&amp; (foo = params[<span class="Constant">:foo</span>])
  <span class="Comment"># ..</span>
<span class="Conditional">end</span>

<span class="Comment"># with presence:</span>
<span class="Conditional">if</span> foo = params[<span class="Constant">:foo</span>].presence
  <span class="Comment"># ...</span>
<span class="Conditional">end</span>

<span class="Comment"># The example Rails gives:</span>
state   = params[<span class="Constant">:state</span>]   <span class="Conditional">if</span> params[<span class="Constant">:state</span>].present?
country = params[<span class="Constant">:country</span>] <span class="Conditional">if</span> params[<span class="Constant">:country</span>].present?
region  = state || country || <span class="rubyStringDelimiter">'</span><span class="String">US</span><span class="rubyStringDelimiter">'</span>
<span class="Comment"># ...becomes:</span>
region = params[<span class="Constant">:state</span>].presence || params[<span class="Constant">:country</span>].presence || <span class="rubyStringDelimiter">'</span><span class="String">US</span><span class="rubyStringDelimiter">'</span></pre>
<p>I like this way of cleaning up you&#39;re code. I guess it&#39;s Rubyesque to feel the need to tidy and shorten your code like this.</p>

<h3 id="toc_1">uniq_by</h3>

<p>Another funny one is <code>Array.uniq_by</code> (and it sister-with-a-bang-method). It works as select, but returns only the first element from the array that complies with the block you gave it. Here are some examples to illustrate that:</p>
<pre>[ <span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">4</span> ].uniq_by(&amp;<span class="Constant">:odd?</span>) <span class="Comment"># =&gt; [ 1, 2 ]</span>

posts = <span class="rubyStringDelimiter">%W"</span><span class="String">foo bar foo</span><span class="rubyStringDelimiter">"</span>.map.with_index <span class="rubyControl">do</span> |<span class="Identifier">title</span>, <span class="Identifier">i</span>|
  <span class="Type">Post</span>.create(<span class="Constant">:title</span> =&gt; title, <span class="Constant">:index</span> =&gt; i)
<span class="rubyControl">end</span>
posts.uniq_by(&amp;<span class="Constant">:title</span>)
<span class="Comment"># =&gt; [ Post("foo", 0), Post("bar", 1) ] ( and not Post("foo", 2) )</span>

some_array.uniq_by(&amp;<span class="Constant">:object_id</span>) <span class="Comment"># same as some_array.uniq</span></pre>
<h3 id="toc_2">exclude?</h3>

<p>And the final one for today is <code>exclude?</code> which is the opposite of <code>include?</code>. Nobody likes the exclamation mark before predicate methods.</p>
<pre><span class="Comment"># yuck:</span>
!some_array.include?(some_value)
<span class="Comment"># better:</span>
some_array.exclude?(some_value)</pre>
<p>And it also works on strings:</p>
<pre><span class="Comment"># even more yuck:</span>
!<span class="rubyStringDelimiter">"</span><span class="String">The quick fox</span><span class="rubyStringDelimiter">"</span>.include?(<span class="rubyStringDelimiter">"</span><span class="String">quick</span><span class="rubyStringDelimiter">"</span>) <span class="Comment"># =&gt; false</span>
<span class="Comment"># better:</span>
<span class="rubyStringDelimiter">"</span><span class="String">The quick fox</span><span class="rubyStringDelimiter">"</span>.exclude?(<span class="rubyStringDelimiter">"</span><span class="String">quick</span><span class="rubyStringDelimiter">"</span>) <span class="Comment"># =&gt; false</span></pre>
<p>The full release notes of Rails 3 can be <a href="http://guides.rails.info/3_0_release_notes.html">read here</a>.</p>
]]>
      </description>
      <guid>http://iain.nl/3-times-activesupport-3</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>http_accept_language released as a gem</title>
      <link>http://iain.nl/http_accept_language-released-as-a-gem</link>
      <pubDate>Tue, 05 Jan 2010 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I released an old Rails plugin as gem today. Slowly but surely, all my plugins will be converted to gems.</p>

<p>This time it&#39;s an old one: <a href="http://github.com/iain/http_accept_language">http_accept_language</a></p>

<ul>
<li>Splits the http-header into languages specified by the user</li>
<li>Returns empty array if header is illformed.</li>
<li>Corrects case to xx-XX</li>
<li>Sorted by priority given, as much as possible.</li>
<li>Gives you the most important language</li>
<li>Gives compatible languages</li>
</ul>

<p>For more information, read the README on GitHub.</p>
]]>
      </description>
      <guid>http://iain.nl/http_accept_language-released-as-a-gem</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Basic Named Scopes</title>
      <link>http://iain.nl/basic_named_scopes</link>
      <pubDate>Tue, 22 Dec 2009 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Cal it tiny, I don&#39;t care. I&#39;ve made a gem named <a href="http://github.com/iain/basic_named_scopes">BasicNamedScopes</a>.</p>

<h3 id="toc_0">Basic Usage</h3>

<p>I was fed up with writing:</p>
<pre><span class="Type">Post</span>.all(<span class="Constant">:conditions</span> =&gt; { <span class="Constant">:published</span> =&gt; <span class="Constant">true</span> }, <span class="Constant">:select</span> =&gt; <span class="Constant">:title</span>, <span class="Constant">:include</span> =&gt; <span class="Constant">:author</span>)</pre>
<p>So with BasicNamedScopes, you can now write:</p>

<p>Post.conditions(:published =&gt; true).select(:title).with(:author)</p>

<p>All named scopes are called the same, except for <code>include</code>, which is now called <code>with</code>, because <code>include</code> is a reserved method.</p>

<p>Reuse them by making class methods:</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">published</span>
    conditions(<span class="Constant">:published</span> =&gt; <span class="Constant">true</span>)
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">visible</span>
    conditions(<span class="Constant">:visible</span> =&gt; <span class="Constant">true</span>)
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">index</span>
    published.visible
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Also, the <code>all</code>-method is a named scope now, so you can chain after callling <code>all</code>, for greater flexibility.</p>
<pre><span class="Type">Post</span>.all.published</pre>
<p>Arrays can be used as multple parameters too, sparing you some brackets.</p>
<pre><span class="Type">Post</span>.with(<span class="Constant">:author</span>, <span class="Constant">:comments</span>).conditions(<span class="rubyStringDelimiter">"</span><span class="String">name LIKE ?</span><span class="rubyStringDelimiter">"</span>, query)</pre>
<p>The <code>read_only</code> and <code>lock</code> scopes default to true, but can be adjusted.</p>
<pre><span class="Type">Post</span>.readonly         <span class="Comment"># =&gt; same as Post.all(:readonly =&gt; true)</span>
<span class="Type">Post</span>.readonly(<span class="Constant">false</span>)  <span class="Comment"># =&gt; same as Post.all(:readonly =&gt; false)</span></pre>
<h3 id="toc_1">Why?</h3>

<p>NamedScopes are really handy and they should play a more central theme in ActiveRecord. While I heard that Rails 3 will support similar syntax, there is no reason to wait any longer.</p>

<p>I find defining named scopes very ugly, especially when dealing with parameters. Just compare the amount of curly braces!</p>
<pre><span class="Comment"># Using normal named scope:</span>
named_scope <span class="Constant">:name_like</span>, <span class="Keyword">lambda</span> { |<span class="Identifier">query</span>| { <span class="Constant">:conditions</span> =&gt; [<span class="rubyStringDelimiter">"</span><span class="String">name LIKE ?</span><span class="rubyStringDelimiter">"</span>, query] } }

<span class="Comment"># Using BasicNamedScopes</span>
<span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">name_like</span>(query)
  conditions(<span class="rubyStringDelimiter">"</span><span class="String">name LIKE ?</span><span class="rubyStringDelimiter">"</span>, query)
<span class="PreProc">end</span></pre>
<p>Also, regular named scopes don&#39;t support using other named scopes at all!</p>

<p>I found myself implementing these named scopes (mostly conditions, but others too) so often, that a little gem like this would be the obvious choice. Use it if a gem like <a href="http://github.com/binarylogic/searchlogic">searchlogic</a> is overkill for your needs.</p>

<h3 id="toc_2">Installing</h3>

<p>The gem is called &quot;basic_named_scopes&quot;. You know how to install it.</p>
<pre>gem <span class="Statement">install</span> basic_named_scopes</pre>
<p>Use it in Rails:</p>
<pre>config.gem <span class="rubyStringDelimiter">"</span><span class="String">basic_named_scopes</span><span class="rubyStringDelimiter">"</span></pre>
<h12 id="toc_41943040">Update</h3>

<p>The syntax is fully compatible with ActiveRecord 3, and if you&#39;re using ActiveRecord 3, you don&#39;t need to use this gem.</p>
]]>
      </description>
      <guid>http://iain.nl/basic_named_scopes</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Cucumber 0.5 and my little commit</title>
      <link>http://iain.nl/cucumber-0-5-and-my-little-commit</link>
      <pubDate>Fri, 18 Dec 2009 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>The strangest thing happened to me this week. I was working on a little
side project at work. It seemed like a nice time to try out some new gems
(<a href="http://gemcutter.org/gems/bundler">Bundler</a> and <a href="http://gemcutter.org/gems/devise">Devise</a>:
love it! <a href="http://gemcutter.org/gems/inherited_resources">InheritedResources</a>, not that much,
<a href="http://gemcutter.org/gems/formtastic">Formtastic</a>, very nice). I was experimenting with
<a href="http://cukes.info">Cucumber</a> and writing Dutch features too.</p>

<p>I had figured that the supplied dutch keywords in
<a href="http://github.com/aslakhellesoy/cucumber/blob/master/lib/cucumber/languages.yml#L328%0A-340">languages.yml</a> were not very practical. It supplied &quot;<em>Gegeven</em>&quot; as a naive translation of &quot;<em>Given</em>&quot;. Although
this is correctly translated, it is very unpractical to form Dutch sentences with it. The only to
really start a sentence with &quot;<em>Gegeven</em>&quot; is to write &quot;<em>Gegeven het feit dat...</em>&quot; (&quot;<em>Given the fact
that...</em>&quot;). It&#39;s very strange to say &quot;<em>Gegeven dat ik een profiel heb</em>&quot; (&quot;<em>Given I have a profile</em>&quot;)
in Dutch.</p>

<p>I decided to use the synonym &quot;<em>Stel</em>&quot; like in &quot;<em>Stel ik heb een profiel</em>&quot;. Not entirely correct
either because it misses a comma after &quot;<em>Stel</em>&quot;, but much better, in my honest opinion. So I forked
cucumber, changed <code>languages.yml</code> and used this as custom git repository in my <code>Gemfile</code>.</p>

<p>Apparently I was in the middle of a Release Candidate, so what I had committed on
github. The Rails integration was extracted out in that version (like RSpec does) to the
&quot;<a href="http://github.com/aslakhellesoy/cucumber-rails">cucumber-rails</a>&quot; gem. This gave about an evening
of confusion, but I got it to work eventually.</p>

<p>Two days later, we had visitors at our company, from another Ruby company, talking about cooperation
on future projects. I introduced myself and he was trying to remember if he&#39;d seen anything on the
interwebs by me. That seems to be common. When meeting people on conferences it&#39;s always the same
question: &quot;Do I know any of your gems?&quot;.</p>

<p>Anyway, he had actually read my name recently, namely in the commit log of cucumber. Without asking
or sending a pull request, they had added my commit to the 0.5 release of cucumber. A pleasant
surprise! Aslak Hellesøy, you&#39;re a very observant <a href="http://github.com/aslakhellesoy">GitHub user</a>!</p>

<p>By the way, you can still use &quot;<em>Gegeven</em>&quot;, as it is just an alias.</p>

<p>I am constantly wrestling with the best way write cucumber features down. Does anyone have Dutch
features? Do you write them down with your customers or are they for developers only? Can you share
some of them? Here are some of mine:</p>
<pre><span class="PreProc">Scenario:</span> Inloggen
  <span class="Conditional">Stel</span> ik ben uitgelogd
  <span class="Conditional">En</span> ik heb een account voor "gebruiker@test.com" met het wachtwoord "geheim"
  <span class="Conditional">En</span> ik ben op de inlogpagina
  <span class="Function">Als</span> ik de volgende velden invul:
    <span class="Delimiter">|</span> E-mailadres <span class="Delimiter">|</span> gebruiker@test.com  <span class="Delimiter">|</span>
    <span class="Delimiter">|</span> Wachtwoord  <span class="Delimiter">|</span> geheim              <span class="Delimiter">|</span>
  <span class="Function">En</span> ik op "Inloggen" druk
  <span class="Function">Dan</span> zie ik de melding "Je bent ingelogd"

<span class="PreProc">Scenario:</span> Verkeerd wachtwoord
  <span class="Conditional">Stel</span> ik ben uitgelogd
  <span class="Conditional">En</span> ik heb een account voor "gebruiker@test.com" met het wachtwoord "geheim"
  <span class="Conditional">En</span> ik ben op de inlogpagina
  <span class="Function">Als</span> ik de volgende velden invul:
    <span class="Delimiter">|</span> E-mailadres <span class="Delimiter">|</span> gebruiker@test.com  <span class="Delimiter">|</span>
    <span class="Delimiter">|</span> Wachtwoord  <span class="Delimiter">|</span> verkeerd            <span class="Delimiter">|</span>
  <span class="Function">En</span> ik op "Inloggen" druk
  <span class="Function">Dan</span> zie ik de foutmelding "Ongeldig e-mailadres of wachtwoord"</pre>
<p>By the way, don&#39;t forget to order the <a href="http://pragprog.com/titles/achbd/the-rspec-book">RSpec and Friends
book</a>. It&#39;ll be released this februari and is a
really good read if you want to learn BDD, RSpec or Cucumber.</p>
]]>
      </description>
      <guid>http://iain.nl/cucumber-0-5-and-my-little-commit</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Prawn and controller tests</title>
      <link>http://iain.nl/prawn-and-controller-tests</link>
      <pubDate>Wed, 18 Nov 2009 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>There is a real annoying gotcha in using controller tests to test an action that renders a pdf with
<a href="http://prawn.majesticseacreature.com/">Prawn</a>. You&#39;ll get a NoMethodException on &quot;nil.downcase&quot;.
The troubling part is that it totally puts you off by providing the wrong lines and backtrace.</p>

<p>This has been mentioned somewhere on some
<a href="http://groups.google.com/group/prawn-ruby/browse_thread/thread/a44c7647894d165c">mailinglists</a>, but
to make it a bit more findable, I&#39;d thought I&#39;d post it here.</p>

<p>The <del>solution</del> workaround is to set the server protocol, like this:</p>
<pre>it <span class="rubyStringDelimiter">"</span><span class="String">should show the pdf</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>
  request.env[<span class="rubyStringDelimiter">"</span><span class="String">SERVER_PROTOCOL</span><span class="rubyStringDelimiter">"</span>] = <span class="rubyStringDelimiter">"</span><span class="String">http</span><span class="rubyStringDelimiter">"</span>
  get <span class="Constant">:show</span>, <span class="Constant">:id</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">report</span><span class="rubyStringDelimiter">"</span>, <span class="rubyStringDelimiter">"</span><span class="String">format</span><span class="rubyStringDelimiter">"</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">pdf</span><span class="rubyStringDelimiter">"</span>
  response.should render_template(<span class="Constant">:show</span>)
<span class="rubyControl">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/prawn-and-controller-tests</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Configuring Autotest</title>
      <link>http://iain.nl/configuring-autotest</link>
      <pubDate>Fri, 09 Oct 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I have a big test suite in the current Rails application I&#39;m working on. I have 2340 examples in
RSpec, taking over 2 minutes to run. This is an absolute pain to run. Luckily there is autotest (or
autospec if you&#39;re running RSpec, like I am), which tests only the changed files. I&#39;ve grown to be
totally dependent on this behavior, and I can&#39;t imagine programming without it anymore.</p>

<p>I also do TDD, which means that I write a failing test first, and then program until it passes. But
Autotest&#39;s flow is that, once you&#39;ve fixed a failing test or spec, it reruns the entire the suite to
see if you&#39;re solution doesn&#39;t have any side effects. Normally this is fine, but with this kind of
test suite, I cannot afford to wait for it to complete.</p>

<p>So, after going through Autotest&#39;s code, I&#39;ve decided to stub out this behavior. You can still
trigger a complete rerun of the entire suite by pressing Ctrl+C, but it doesn&#39;t do that every time
you go green. It&#39;s a bit of a monkey patch, but it works just right.</p>

<p>The autotest-growl gem clears the terminal. I don&#39;t like that, because I like to see a bit of
history. That&#39;s why I changed that behavior too.</p>

<p>Here&#39;s my <code>~&#47;.autotest</code> file:</p>
<pre><span class="Comment"># Use file system hooks on OS X</span>
<span class="PreProc">require</span> <span class="rubyStringDelimiter">'</span><span class="String">autotest/fsevent</span><span class="rubyStringDelimiter">'</span>

<span class="Comment"># Don't run entire test suite when going from red to green</span>
<span class="Keyword">class</span> <span class="Type">Autotest</span>
  <span class="PreProc">def</span> <span class="Function">tainted</span>
    <span class="Constant">false</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span>

<span class="Comment"># Use Growl support</span>
<span class="PreProc">require</span> <span class="rubyStringDelimiter">'</span><span class="String">autotest/growl</span><span class="rubyStringDelimiter">'</span>

<span class="Comment"># Don't clear the terminal, when using Growl</span>
<span class="Keyword">module</span> <span class="Type">Autotest</span>::<span class="Type">Growl</span>
  <span class="Identifier">@@clear_terminal</span> = <span class="Constant">false</span>
<span class="Keyword">end</span></pre>
<p>While browsing through the code of Autotest I also found that it also looks for a <code>.autotest</code> file
in the current working directory. So if you want to apply these changes to one project only, you can
define this file locally for the project. I didn&#39;t know that!</p>
]]>
      </description>
      <guid>http://iain.nl/configuring-autotest</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Plugin release: Root table</title>
      <link>http://iain.nl/root-table</link>
      <pubDate>Sun, 19 Jul 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Yes, I&#39;ve written another plugin for Rails. It&#39;s about so called root tables. It seem to be making
them often. I want a list with options to choose from and some easy way to manage that list, which
is a tedious task. That&#39;s why I made a <a href="http://github.com/iain/root_table">plugin</a> to do this for
me.</p>

<h3 id="toc_0">What I have so far is:</h3>

<ul>
<li>Automatic validations and relations</li>
<li>Completely configurable, with sensible defaults</li>
<li>A management interface</li>
<li>Works with <a href="http://github.com/rails/acts_as_list">acts_as_list</a> and supports drag and drop sorting</li>
<li>I18n support</li>
</ul>

<h3 id="toc_1">Let&#39;s take a tour of it&#39;s usage.</h3>

<p>Install acts_as_list, if you want to:</p>
<pre>./script/plugin install git://github.com/rails/acts_as_list.git
</pre>
<p>Install root_table:</p>
<pre>./script/plugin install git://github.com/iain/root_table.git
</pre>
<p>Make a model that needs a list to choose from, like a product that has a category:</p>
<pre>./script/genetate model Product name:string category_id:integer
</pre>
<p>Make a model for the root table, category:</p>
<pre>./script/generate model Category name:string position:integer
</pre>
<p>Make category a root table for product:</p>
<pre><span class="Keyword">class</span> <span class="Type">Category</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  root_table_for <span class="Constant">:product</span>
<span class="Keyword">end</span></pre>
<p>And let the product model know as well what is happening:</p>
<pre><span class="Keyword">class</span> <span class="Type">Product</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  has_root_table <span class="Constant">:category</span>
<span class="Keyword">end</span></pre>
<p>Let&#39;s add a configured root table for good measure. Let&#39;s convert the User-model to a root table.
User is not a list, and doesn&#39;t have a <code>name</code>-field to recognize it, nor does it have a position
field. It requires some options to make it work.</p>
<pre><span class="Keyword">class</span> <span class="Type">User</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  root_table_for <span class="Constant">:product</span>, <span class="Constant">:to</span> =&gt; <span class="Constant">:last_edited_by</span>,
      <span class="Constant">:validate</span> =&gt; <span class="Constant">false</span>, <span class="Constant">:field</span> =&gt; <span class="Constant">:login</span>
<span class="Keyword">end</span></pre>
<p>And update the product model again:</p>
<pre><span class="Keyword">class</span> <span class="Type">Product</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  has_root_table <span class="Constant">:category</span>
  has_root_table <span class="Constant">:user</span>
<span class="Keyword">end</span></pre>
<p>The relation is called <code>last_edited_by</code>, it doesn&#39;t add any validations and the displayed (and thus
sorted) field is <code>login</code> instead of <code>name</code>. It doesn&#39;t have position field, nor do I provide it, so
it&#39;ll sort on <code>login</code> and won&#39;t be manually sortable, as we&#39;ll se in a bit.</p>

<p><small>Using the User model might not be the best example, but you&#39;ll get the point.</small></p>

<h3 id="toc_2">Management in a Rails Engine</h3>

<p>Visit the management interface at <code>http:&#47;&#47;localhost:3000&#47;root_tables</code> and see something like this:</p>

<p><img src="/root_tables_path.png" alt="root_tables_path" title="root_tables_path" width="508" height="339" class="alignnone size-full wp-image-478" /></p>

<p>Since User has no position field, you&#39;ll end up with a simple scaffold-like management screen for it:</p>

<p><img src="/root_table_contents_pathuser.png" alt="root_table_contents_path(user)" title="root_table_contents_path(user)" width="508" height="339" class="alignnone size-full wp-image-479" /></p>

<p>However, the Category model does have a position, so the interface has drag and drop functionality:</p>

<p><img src="/root_table_contents_pathcategory.png" alt="root_table_contents_path(category)" title="root_table_contents_path(category)" width="508" height="339" class="alignnone size-full wp-image-480" /></p>

<p>It has a very simple new and edit screen, just as you would with scaffold:</p>

<p><img src="/edit_root_table_contents_path.png" alt="edit_root_table_contents_path" title="edit_root_table_contents_path" width="508" height="339" class="alignnone size-full wp-image-481" /></p>

<p>This is all done with a layout that Rails scaffold generates. If you have your own layout it might
look completely different. The management pages are a Rails engine. This means that you can override
any file by creating a file with the same name in your <code>app</code>-directory. Have a look at the code to
see which files you can override.</p>

<p>Also, to enable the drag and drop interface, you&#39;ll need to have prototype included. If you don&#39;t
want prototype be loaded everywhere, I&#39;ve made it so that only drag and drop pages load the
javascript. Please add <tt>&lt;%= yield(:head) %&gt;</tt> to your html header.</p>

<p>You can also override views on a table basis. That means that you might want a view that is
different just in case of one table. The form for new users might want to have more fields
than just the login field, but also include password fields. Create a view for that in
<code>app&#47;views&#47;root_table_contents&#47;new_user.html.erb</code>. Available for override per model are index, new
and edit.</p>

<h3 id="toc_3">Using it elsewhere</h3>

<p>But we&#39;re not there yet. Now we&#39;ve built a root table and filled it, we need to use it somewhere. The plugin provides a <code>root_table_select</code> helper, that renders a drop down. The first parameter is the root_tables (real) name, it figures the rest out automatically. You can pass any options as the options you would pass the other select helpers. Here&#39;s an example:</p>
<pre><span class="PreProc">&lt;%</span> form_for <span class="Identifier">@product</span> <span class="rubyControl">do</span> |<span class="Identifier">f</span>| <span class="PreProc">%&gt;</span>
  <span class="Keyword">&lt;</span><span class="Conditional">p</span><span class="Keyword">&gt;</span>
    <span class="PreProc">&lt;%=</span> f.label <span class="Constant">:category_id</span> <span class="PreProc">%&gt;</span><span class="Keyword">&lt;</span><span class="Conditional">br</span><span class="Keyword"> /&gt;</span>
    <span class="PreProc">&lt;%=</span> f.root_table_select <span class="Constant">:category</span>, <span class="Constant">:include_blank</span> =&gt; <span class="Constant">true</span> <span class="PreProc">%&gt;</span>
  <span class="Identifier">&lt;/</span><span class="Conditional">p</span><span class="Identifier">&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>Also for showing a delegate method is provided. This is how you can show the category name:</p>
<pre><span class="Identifier">@product</span>.category_name</pre>
<p>That about wraps it up for <a href="http://github.com/iain/root_table">root_table</a>. Please provide me with
feedback and report any bugs and improvements. You can use the comments on my blog, or the <a href="http://github.com/iain/root_table/issues">issues
page on github</a>.</p>

<h3 id="toc_4">Update!</h3>

<p>I&#39;ve made some tiny updates, most importantly reducing the amount of magic. Rails does a very nice job of lazy loading your models which can lead to some strange errors with the previous version of my plugin. These should be fixed now.</p>

<h3 id="toc_5">Lessons learned:</h3>

<ul>
<li>A model does not know another model exist in development environment. Mentioning a model is enough to trigger Rails autoload and even constantizing a string works. Sweet!</li>
<li>Don&#39;t require a model again during a request. Some models will break. I found this to be the case with the session class needed by AuthLogic. Again, to know for sure that a model has been loaded, simply mention it in your code, usually that is enough.</li>
<li>Tests are run in an environment very similar to production. I already knew that, but it&#39;s worth mentioning that a stable development environment is also essential and you might not catch that with unit tests alone.</li>
</ul>
]]>
      </description>
      <guid>http://iain.nl/root-table</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Silencing Passenger</title>
      <link>http://iain.nl/silencing-passenger</link>
      <pubDate>Fri, 19 Jun 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>When using Rails 2.3 and Passenger, you can do yourself a favor by adding this line to
<code>config&#47;silencers&#47;backtrace_silencer.rb</code></p>
<pre><span class="Type">Rails</span>.backtrace_cleaner.add_silencer { |<span class="Identifier">line</span>| line =~ <span class="rubyRegexpDelimiter">/</span><span class="Special">^</span><span class="Special">\s</span><span class="Special">*</span><span class="rubyRegexp">passenger</span><span class="rubyRegexpDelimiter">/</span> }</pre>
<p>Saves you scrolling through the endless backtraces passenger gives you for free :)</p>

<p>PS. A colleague tweeted this <a href="http://twitter.com/pascaldevink/status/2240565349">lovely backtrace</a>
of a spring with grails error. I say: backtrace cleaner FTW!</p>
]]>
      </description>
      <guid>http://iain.nl/silencing-passenger</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Filtering with named scopes (encore)</title>
      <link>http://iain.nl/filtering-with-named-scopes-encore</link>
      <pubDate>Wed, 17 Jun 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>In my previous post, I talked about making filters using named scopes. To summorize:</p>

<blockquote>
<p>I like the method of using a named_scope and delegating to specified filters. This way, you can
structure your filters properly and get clean URLs. Also, you can chain other named scopes to the
filter.</p>
</blockquote>

<p>If you find yourself making an administrative web application, with many tables and filters, here&#39;s
an example to make it a little more DRY.</p>

<h3 id="toc_0">Making a partial</h3>

<p>First, make the filters a partial, in something like <code>app&#47;views&#47;shared&#47;_filters.html.haml</code>.</p>
<pre><span class="Special">%</span><span class="Conditional">h3</span><span class="Special">=</span> t(model_name, <span class="Constant">:scope</span> =&gt; <span class="Constant">:filter_titles</span>)
<span class="Special">%</span><span class="Conditional">ul</span>
  <span class="Special">-</span> model_class.available_filters.each <span class="rubyControl">do</span> |<span class="Identifier">filter</span>|
    <span class="Special">%</span><span class="Conditional">li</span><span class="Special">=</span> link_to t(filter, <span class="Constant">:scope</span> =&gt; [<span class="Constant">:filter_names</span>, model_name]), url_for(params.merge(<span class="Constant">:filter</span> =&gt; filter))</pre>
<p>I&#39;ve changed the translate-calls a bit, so they work with different models.</p>

<h3 id="toc_1">A helper method</h3>

<p>Then, create a helper method:</p>
<pre><span class="PreProc">def</span> <span class="Function">show_filters_for</span>(model_name)
  render <span class="Constant">:partial</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">shared/filters</span><span class="rubyStringDelimiter">"</span>,
         <span class="Constant">:locals</span> =&gt; { <span class="Constant">:model_name</span> =&gt; model_name, <span class="Constant">:model_class</span> =&gt; model_name.to_s.camilze.constantize }
<span class="PreProc">end</span></pre>
<p>Now you can render the filters like this:</p>
<pre><span class="Special">=</span> show_filters_for <span class="Constant">:person</span></pre>
<h3 id="toc_2">And a module</h3>

<p>On the model side, you can make a module, probably in <code>lib&#47;chainable_filters.rb</code>.</p>
<pre><span class="Keyword">module</span> <span class="Type">ChainableFilters</span>

  <span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">extended</span>(model)
    model.named_scope <span class="Constant">:filter</span>, <span class="Keyword">lambda</span> { |<span class="Identifier">f</span>|
      model.available_filters.include?(f) ? model.send(<span class="rubyStringDelimiter">"</span><span class="String">filter_</span><span class="rubyInterpolationDelimiter">#{</span>f<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>) : {}
    }
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">available_filters</span>
    <span class="Constant">self</span>.methods.select { |<span class="Identifier">m</span>| m =~ <span class="rubyRegexpDelimiter">/</span><span class="Special">^</span><span class="rubyRegexp">filter_</span><span class="rubyRegexpDelimiter">/</span> }.map { |<span class="Identifier">m</span>| m[<span class="Number">7</span>..<span class="Number">-1</span>].to_sym }
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>Use it in a specific model, by extending with the module you just made:</p>
<pre><span class="Keyword">class</span> <span class="Type">Person</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  <span class="PreProc">extend</span> <span class="Type">ChainableFilters</span>
<span class="Keyword">end</span></pre>
<p>Or just every ActiveRecord class, by creating an initializer file (i.e. <code>config&#47;initializers&#47;chainable_filters.rb</code>):</p>
<pre><span class="Type">ActiveRecord</span>::<span class="Type">Base</span>.extend <span class="Type">ChainableFilters</span></pre>
<p>Now, that is some nice meta-programming, if you ask me! ;)</p>
]]>
      </description>
      <guid>http://iain.nl/filtering-with-named-scopes-encore</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Filtering with named scopes</title>
      <link>http://iain.nl/filtering-with-named-scopes</link>
      <pubDate>Fri, 12 Jun 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Suppose you have an index page with people and you want to have a series of neat filters to show a
selection of people. For example only the people still alive of only the adults. How would one do
that?</p>

<p>I like the method of using a
<a href="http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/named_scope">named_scope</a> and
delegating to specified filters. This way, you can structure your filters properly and get clean
URLs. Also, you can chain other named scopes to the filter.</p>

<p>This is an example of how I would do that.</p>

<h3 id="toc_0">The view</h3>

<p>In your index view, add a list of all filters:</p>
<pre><span class="Special">%</span><span class="Conditional">h3</span><span class="Special">=</span> t(<span class="Constant">:people</span>, <span class="Constant">:scope</span> =&gt; <span class="Constant">:filter_titles</span>)
<span class="Special">%</span><span class="Conditional">ul</span>
  <span class="Special">-</span> <span class="Type">Person</span>.available_filters.each <span class="rubyControl">do</span> |<span class="Identifier">filter</span>|
    <span class="Special">%</span><span class="Conditional">li</span><span class="Special">=</span> link_to t(filter, <span class="Constant">:scope</span> =&gt; [<span class="Constant">:filter_names</span>, <span class="Constant">:people</span>]), people_path(<span class="Constant">:filter</span> =&gt; filter)</pre>
<p>This will generate links that go to your index page (e.g. <code>&#47;people?filter=adults</code>). You can even
make a route that will clean up your views even more.</p>
<pre>map.connect <span class="rubyStringDelimiter">"</span><span class="String">/people/filter/:filter</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">people</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:action</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">index</span><span class="rubyStringDelimiter">"</span></pre>
<p>I use i18n to get the displayed link text for each link, so my locale file might look something
like:</p>
<pre><span class="Identifier">en</span><span class="Special">:</span>
  <span class="Identifier">filter_titles</span><span class="Special">:</span>
    <span class="Identifier">people</span><span class="Special">:</span> Select a subset
  <span class="Identifier">filter_names</span><span class="Special">:</span>
    <span class="Identifier">people</span><span class="Special">:</span>
      <span class="Identifier">deceased</span><span class="Special">:</span> Select deceased people
      <span class="Identifier">alive</span><span class="Special">:</span> Select people that are (still) alive
      <span class="Identifier">adults</span><span class="Special">:</span> Select people over <span class="Number">18</span></pre>
<h3 id="toc_1">The controller</h3>

<p>Add the <code>named_scope</code> to your query:</p>
<pre><span class="PreProc">def</span> <span class="Function">index</span>
  <span class="Identifier">@people</span> = <span class="Type">Person</span>.filter(params[<span class="Constant">:filter</span>]).paginate(<span class="Constant">:page</span> =&gt; params[<span class="Constant">:page</span>])
<span class="PreProc">end</span></pre>
<h3 id="toc_2">The model</h3>

<p>Here&#39;s the interesting stuff. Define the available filters as a class method:</p>
<pre><span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">available_filters</span>
  [ <span class="Constant">:deceased</span>, <span class="Constant">:alive</span>, <span class="Constant">:adults</span> ]
<span class="PreProc">end</span></pre>
<p>Then, define class methods for each those filters, specifying what they need to
do. I like to prepend them with &quot;<code>filter_</code>&quot;, so it shows more intent. You can go
crazy with these filter methods if you&#39;d like. Just return valid <a href="http://apidock.com/rails/ActiveRecord/Base/find/class">ActiveRecord
find-options</a>.</p>
<pre><span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">filter_deceased</span>
  { <span class="Constant">:conditions</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">deceased_on IS NOT NULL</span><span class="rubyStringDelimiter">"</span> }
<span class="PreProc">end</span></pre><pre><span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">filter_alive</span>
  { <span class="Constant">:conditions</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">deceased_on IS NULL</span><span class="rubyStringDelimiter">"</span> }
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Constant">self</span>.<span class="Function">filter_adults</span>
  { <span class="Constant">:conditions</span> =&gt; [<span class="rubyStringDelimiter">"</span><span class="String">birthday &lt;= ?</span><span class="rubyStringDelimiter">"</span>, <span class="Number">18</span>.years.ago.to_date] }
<span class="PreProc">end</span></pre>
<p>And finally, add the named scope that uses these filters:</p>
<pre>named_scope <span class="Constant">:filter</span>, <span class="Keyword">lambda</span> { |<span class="Identifier">f</span>| available_filters.include?(f) ? send(<span class="rubyStringDelimiter">"</span><span class="String">filter_</span><span class="rubyInterpolationDelimiter">#{</span>f<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>) : {} }</pre>
<p>We check to see if the filter is available, excluding any invalid filter. Also, by default no filter
is given from the controller. Then <code>params[:filter]</code> will be <code>nil</code> and so it won&#39;t try to call
<code>Person.filter_</code>. You can replace the empty hash with a default filter if you like.</p>

<h3 id="toc_3">Conclusion</h3>

<p>These predefined filters can really help the usability of your new fancy web application. And I like
the code too, because it looks very clear and it&#39;s easy to test.</p>

<p>Named scopes can get quite messy, certainly if you use a lambda and some logic. Delegating the body
of the lambda to a class method is a good idea. Just be sure that the method returns a hash of some
sort.</p>
<pre>named_scope <span class="Constant">:foo</span>, <span class="Keyword">lambda</span> { |*<span class="Identifier">args</span>| foo_parameters(*args) }</pre>
<p>You can make this into a named_scope generator even, but I&#39;ll save that for another time and post.
Also, stay tuned for the encore: DRYing up the code for re-use!</p>
]]>
      </description>
      <guid>http://iain.nl/filtering-with-named-scopes</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Writing YAML files</title>
      <link>http://iain.nl/writing-yaml-files</link>
      <pubDate>Fri, 15 May 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>A short one for today: How do I write <a href="http://en.wikipedia.org/wiki/YAML">YAML</a> files?</p>

<p>Well, to get the prettiest results, I do something like this:</p>
<pre><span class="PreProc">def</span> <span class="Function">write</span>(filename, hash)
  <span class="Type">File</span>.open(filename, <span class="rubyStringDelimiter">"</span><span class="String">w</span><span class="rubyStringDelimiter">"</span>) <span class="rubyControl">do</span> |<span class="Identifier">f</span>|
    f.write(yaml(hash))
  <span class="rubyControl">end</span>
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Function">yaml</span>(hash)
  method = hash.respond_to?(<span class="Constant">:ya2yaml</span>) ? <span class="Constant">:ya2yaml</span> : <span class="Constant">:to_yaml</span>
  string = hash.deep_stringify_keys.send(method)
  string.gsub(<span class="rubyStringDelimiter">"</span><span class="String">!ruby/symbol </span><span class="rubyStringDelimiter">"</span>, <span class="rubyStringDelimiter">"</span><span class="String">:</span><span class="rubyStringDelimiter">"</span>).sub(<span class="rubyStringDelimiter">"</span><span class="String">---</span><span class="rubyStringDelimiter">"</span>,<span class="rubyStringDelimiter">""</span>).split(<span class="rubyStringDelimiter">"</span><span class="Special">\n</span><span class="rubyStringDelimiter">"</span>).map(&amp;<span class="Constant">:rstrip</span>).join(<span class="rubyStringDelimiter">"</span><span class="Special">\n</span><span class="rubyStringDelimiter">"</span>).strip
<span class="PreProc">end</span></pre>
<p>I use the gem <a href="http://rubyforge.org/projects/ya2yaml/">ya2yaml</a> to create YAML, because the default
Hash#to_yaml doesn&#39;t work well with UTF-8. If you have it installed and loaded, it uses that.</p>

<p>Then I turn all keys into strings with the method <code>deep_stringify_keys</code>, so the keys don&#39;t get
formatted like the symbols they are. I remove some random junk and strip whitespace.</p>

<p>To add the <code>deep_stringify_keys</code>, open the Hash class:</p>
<pre><span class="Keyword">class</span> <span class="Type">Hash</span>
  <span class="PreProc">def</span> <span class="Function">deep_stringify_keys</span>
    new_hash = {}
    <span class="Constant">self</span>.each <span class="rubyControl">do</span> |<span class="Identifier">key</span>, <span class="Identifier">value</span>|
      new_hash.merge!(key.to_s =&gt; (value.is_a?(<span class="Type">Hash</span>) ? value.deep_stringify_keys : value)))
    <span class="rubyControl">end</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Here are the specs for this:</p>
<pre><span class="Keyword">class</span> <span class="Type">Hash</span>
  <span class="PreProc">def</span> <span class="Function">deep_stringify_keys</span>
    new_hash = {}
    <span class="Constant">self</span>.each <span class="rubyControl">do</span> |<span class="Identifier">key</span>, <span class="Identifier">value</span>|
      new_hash.merge!(key.to_s =&gt; (value.is_a?(<span class="Type">Hash</span>) ? value.deep_stringify_keys : value)))
    <span class="rubyControl">end</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/writing-yaml-files</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Nested Forms</title>
      <link>http://iain.nl/nested-forms</link>
      <pubDate>Sat, 02 May 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>The old subject of nested forms comes back again to hunt me. Rails 2.3 has the new and shiny
<code>accepts_nested_attributes_for</code> feature. I like it, but there are some things to take into
consideration. Adding a child object through javascript remains a bitch to tackle. So I sat down and
wrote some javascript. Here is what I came up with. Not sure if I&#39;m going to release this a plugin
though.</p>

<p>First of, build the models. I have a project with many stages:</p>
<pre><span class="Keyword">class</span> <span class="Type">Project</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  validates_presence_of <span class="Constant">:name</span>
  has_many <span class="Constant">:stages</span>
  accepts_nested_attributes_for <span class="Constant">:stages</span>, <span class="Constant">:allow_destroy</span> =&gt; <span class="Constant">true</span>
<span class="Keyword">end</span>

<span class="Keyword">class</span> <span class="Type">Stage</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  validates_presence_of <span class="Constant">:title</span>
  belongs_to <span class="Constant">:project</span>
<span class="Keyword">end</span></pre>
<p>Here is what the form partial for the project looks like:</p>
<pre><span class="Special">-</span> form_for <span class="Identifier">@project</span> <span class="rubyControl">do</span> |<span class="Identifier">form</span>|
  <span class="Special">%</span><span class="Conditional">p</span>
    <span class="Special">=</span> form.label <span class="Constant">:name</span>
    <span class="Special">=</span> form.text_field <span class="Constant">:name</span>
  <span class="Special">#</span><span class="Identifier">stages</span>
    <span class="Special">-</span> form.fields_for <span class="Constant">:stages</span> <span class="rubyControl">do</span> |<span class="Identifier">fields</span>|
      <span class="Special">=</span> render <span class="Constant">:partial</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">stage</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:locals</span> =&gt; { <span class="Constant">:form</span> =&gt; fields }
  <span class="Special">%</span><span class="Conditional">p</span><span class="Special">=</span> partial_button(f, <span class="Constant">:stage</span>, <span class="rubyStringDelimiter">"</span><span class="String">Add stage</span><span class="rubyStringDelimiter">"</span>)</pre>
<p>And the stage partial:</p>
<pre><span class="Special">.</span><span class="Type">stage</span><span class="Delimiter">[</span>form.object<span class="Delimiter">]</span>
  <span class="Special">%</span><span class="Conditional">p</span>
    <span class="Special">=</span> form.label <span class="Constant">:title</span>
    <span class="Special">=</span> form.text_field <span class="Constant">:title</span>
  <span class="Special">%</span><span class="Conditional">p</span><span class="Special">=</span> remove_partial(form, <span class="rubyStringDelimiter">"</span><span class="String">Remove stage</span><span class="rubyStringDelimiter">"</span>)</pre>
<p>Ok, so nothing to scary there. Nice clean views. Those two helper methods might be scary though. But
apart from that, it&#39;s actually quite normal.</p>

<p>Notice that the square brackets used at the first line of the stage partial either adds a class
&quot;new_stage&quot; or &quot;stage_X&quot; (where X is the id of an existing stage object).</p>

<p>Let&#39;s see what&#39;s inside the <code>partial_button</code> method!</p>
<pre><span class="PreProc">def</span> <span class="Function">partial_button</span>(form, attribute, link_name)
  returning <span class="rubyStringDelimiter">""</span> <span class="rubyControl">do</span> |<span class="Identifier">out</span>|
    base      = form.object.class.to_s.underscore
    singular  = attribute.to_s.underscore
    plural    = singular.pluralize
    id        = <span class="rubyStringDelimiter">"</span><span class="String">add_nested_partial_</span><span class="rubyInterpolationDelimiter">#{</span>base<span class="rubyInterpolationDelimiter">}</span><span class="String">_</span><span class="rubyInterpolationDelimiter">#{</span>singular<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
    form.fields_for attribute.to_s.classify.constantize.new <span class="rubyControl">do</span> |<span class="Identifier">field</span>|
      html = render(<span class="Constant">:partial</span> =&gt; singular, <span class="Constant">:locals</span> =&gt; { <span class="Constant">:form</span> =&gt; field})
      js   = <span class="rubyStringDelimiter">%|</span><span class="String">new NestedFormPartial("</span><span class="rubyInterpolationDelimiter">#{</span>escape_javascript(html)<span class="rubyInterpolationDelimiter">}</span><span class="String">", { parent:"</span><span class="rubyInterpolationDelimiter">#{</span>base<span class="rubyInterpolationDelimiter">}</span><span class="String">", singular:"</span><span class="rubyInterpolationDelimiter">#{</span>singular<span class="rubyInterpolationDelimiter">}</span><span class="String">", plural:"</span><span class="rubyInterpolationDelimiter">#{</span>plural<span class="rubyInterpolationDelimiter">}</span><span class="String">"}).insertHtml();</span><span class="rubyStringDelimiter">|</span>
      out &lt;&lt; hidden_field_tag(<span class="Constant">nil</span>, js, <span class="Constant">:id</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">js_</span><span class="rubyInterpolationDelimiter">#{</span>id<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>) + <span class="rubyStringDelimiter">"</span><span class="Special">\n</span><span class="rubyStringDelimiter">"</span>
      out &lt;&lt; content_tag(<span class="Constant">:input</span>, <span class="Constant">nil</span>, <span class="Constant">:type</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">button</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:value</span> =&gt; link_name, <span class="Constant">:class</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">add_nested_partial</span><span class="rubyStringDelimiter">"</span>, <span class="Constant">:id</span> =&gt; id)
    <span class="rubyControl">end</span>
  <span class="rubyControl">end</span>
<span class="PreProc">end</span></pre>
<p>Ok, this looks scary. But it isn&#39;t that scary. This method returns a string called <code>out</code>. First of I
build some variables, which will be needed as options for the javascript, since javascript doesn&#39;t
have those cool inflections ActiveSupport has.</p>

<p>Second, I am going to make a fields_for block, which you&#39;ll already know what it does. I render the
partial and assign it to the <code>html</code> variable. Then I generate some javascript which initiates a new
<code>NestedFormPartial</code> object. Finally, I build a hidden field, which contains this javascript as value
and a button.</p>

<p>Here&#39;s the javascript, you&#39;ll need to add:</p>
<pre><span class="Identifier">var</span> NestedFormPartial = Class.create();
NestedFormPartial.prototype = <span class="Function">{</span>
  initialize : <span class="Function">function</span>(html, options)<span class="Function">{</span>
    <span class="Identifier">this</span>.newId          = <span class="String">"new_"</span> + <span class="Operator">new</span> <span class="Type">Date</span>().getTime();
    <span class="Identifier">this</span>.html           = html;
    <span class="Identifier">this</span>.parentName     = options<span class="Function">[</span><span class="String">"parent"</span><span class="Function">]</span>;
    <span class="Identifier">this</span>.singularName   = options<span class="Function">[</span><span class="String">"singular"</span><span class="Function">]</span>;
    <span class="Identifier">this</span>.pluralName     = options<span class="Function">[</span><span class="String">"plural"</span><span class="Function">]</span>;
    <span class="Conditional">if</span> (!<span class="Identifier">this</span>.pluralName) <span class="Identifier">this</span>.pluralName = <span class="Identifier">this</span>.singularName + <span class="String">"s"</span>;
    <span class="Identifier">this</span>.replaceHtml();
  <span class="Function">}</span>,
  oldPartialId : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.singularName + <span class="String">"_new"</span>;
  <span class="Function">}</span>,
  oldElementId : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.parentName + <span class="String">"_"</span> + <span class="Identifier">this</span>.singularName + <span class="String">"_"</span>;
  <span class="Function">}</span>,
  oldElementName : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.parentName + <span class="String">"</span><span class="Special">\\</span><span class="String">["</span> + <span class="Identifier">this</span>.singularName + <span class="String">"</span><span class="Special">\\</span><span class="String">]"</span>;
  <span class="Function">}</span>,
  newPartialId : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.singularName + <span class="String">"_"</span> + <span class="Identifier">this</span>.newId;
  <span class="Function">}</span>,
  newElementId : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.parentName + <span class="String">"_"</span> + <span class="Identifier">this</span>.newPartialId() + <span class="String">"_"</span>;
  <span class="Function">}</span>,
  newElementName : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Statement">return</span> <span class="Identifier">this</span>.parentName + <span class="String">"["</span> + <span class="Identifier">this</span>.pluralName + <span class="String">"_attributes]["</span> + <span class="Identifier">this</span>.newId + <span class="String">"]"</span>;
  <span class="Function">}</span>,
  replaceFunction : <span class="Function">function</span>(pattern, replacement) <span class="Function">{</span>
    <span class="Identifier">this</span>.html = <span class="Identifier">this</span>.html.replace(<span class="Operator">new</span> <span class="Type">RegExp</span>(pattern, <span class="String">"g"</span>), replacement);
  <span class="Function">}</span>,
  replaceHtml : <span class="Function">function</span>()<span class="Function">{</span>
    <span class="Identifier">this</span>.replaceFunction(<span class="Identifier">this</span>.oldPartialId(),   <span class="Identifier">this</span>.newPartialId());
    <span class="Identifier">this</span>.replaceFunction(<span class="Identifier">this</span>.oldElementId(),   <span class="Identifier">this</span>.newElementId());
    <span class="Identifier">this</span>.replaceFunction(<span class="Identifier">this</span>.oldElementName(), <span class="Identifier">this</span>.newElementName());
  <span class="Function">}</span>,
  insertHtml : <span class="Function">function</span>()<span class="Function">{</span>
    $(<span class="Identifier">this</span>.pluralName).insert(<span class="Function">{</span> bottom :  <span class="Identifier">this</span>.html <span class="Function">}</span>);
  <span class="Function">}</span>,
<span class="Function">}</span>

<span class="Function">function</span> initPartialButtons() <span class="Function">{</span>
  $$(<span class="String">".add_nested_partial"</span>).each(<span class="Function">function</span>(button, index) <span class="Function">{</span>
    Event.observe(button, <span class="String">"click"</span>, <span class="Function">function</span>(evt) <span class="Function">{</span>
      eval($(<span class="String">"js_"</span> + button.id).value);
    <span class="Function">}</span>)
  <span class="Function">}</span>);
<span class="Function">}</span>

Event.observe(<span class="Keyword">window</span>, <span class="String">'load'</span>, initPartialButtons, <span class="Constant">false</span>);</pre>
<p>Ehm, what did I just do there? Well, the most important thing is that some parts of the partial get
replaced. There are three problems which need to be addressed:</p>

<ul>
<li>A new object always has the same generated id for input fields. Adding two stages would mean that their ids would be the same and that would mean that the labels wouldn&#39;t be clickable (and it wouldn&#39;t be valid html).</li>
<li>Rails wants &quot;stages_attributes&quot; to be included, when providing a new object, it would be named simple &quot;stage&quot;.</li>
<li>Rails expects a hash as stages_attributes. We&#39;ll need to add some arbitrary key, so it&#39;ll turn into a hash.</li>
</ul>

<p>I generate a new id by using the timestamp and replace the values in my html. When the window loads
I find any add_nested_partial class button and eval the value of the hidden field I added earlier,
so the scripts gets executed.</p>

<p>As you can see, I did my best to make this as unobtrusive as possible, but going any further made my head hurt.</p>

<p>Finally, the <code>remove_partial</code> method, which I haven&#39;t cleaned up yet:</p>
<pre><span class="PreProc">def</span> <span class="Function">remove_partial</span>(form, link_name)
  attribute = form.object.class.name.underscore
  <span class="Conditional">if</span> form.object.new_record?
    button_to_function(link_name, <span class="rubyStringDelimiter">"</span><span class="String">$(this).up('.</span><span class="rubyInterpolationDelimiter">#{</span>attribute<span class="rubyInterpolationDelimiter">}</span><span class="String">').remove()</span><span class="rubyStringDelimiter">"</span>)
  <span class="Conditional">else</span>
    form.hidden_field(<span class="Constant">:_delete</span>) +
    button_to_function(link_name, <span class="rubyStringDelimiter">"</span><span class="String">$(this).up('.</span><span class="rubyInterpolationDelimiter">#{</span>attribute<span class="rubyInterpolationDelimiter">}</span><span class="String">').hide(); $(this).previous().value = '1'</span><span class="rubyStringDelimiter">"</span>)
  <span class="Conditional">end</span>
<span class="PreProc">end</span></pre>
<p>I hope this helps. I found a lot of my initial optimism after hearing about
<code>accepts_nested_attributes_for</code> have gone now. It cleans up a lot of code in the model though. I&#39;ll
keep this post updated when I have some improvements.</p>

<p>Sources:</p>

<ul>
<li><a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">Ryan&#39;s Scraps</a></li>
<li><a href="http://github.com/alloy/complex-form-examples/tree/master">Eloy Duran&#39;s complex form examples</a></li>
</ul>
]]>
      </description>
      <guid>http://iain.nl/nested-forms</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Gem cleanup</title>
      <link>http://iain.nl/gem-cleanup</link>
      <pubDate>Sun, 26 Apr 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I was browsing through the gem documentation today, and I found a command that I didn&#39;t know
existed.</p>
<pre>sudo gem cleanup</pre>
<p>It removes old versions of your installed gems. You can of course specify the gems you&#39;d like to
cleanup.</p>
]]>
      </description>
      <guid>http://iain.nl/gem-cleanup</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>RSpec, Shoulda, and custom matchers</title>
      <link>http://iain.nl/rspec-shoulda-and-custom-matchers</link>
      <pubDate>Sat, 11 Apr 2009 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I have been playing with the matchers that Thoughtbot&#39;s
<a href="http://www.thoughtbot.com/projects/shoulda/">Shoulda</a> provides, and they are very cute!</p>

<p>For instance, a controller can be easily tested like this:</p>
<pre>describe <span class="Type">ArticlesController</span> <span class="rubyControl">do</span>

  integrate_views

  describe <span class="rubyStringDelimiter">"</span><span class="String">the index action</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span>

    before <span class="Constant">:each</span> <span class="rubyControl">do</span>
      stub(<span class="Identifier">@article</span> = <span class="Type">Article</span>.new).id { <span class="Number">1337</span> }
      mock(<span class="Type">Article</span>).all { [<span class="Identifier">@article</span>] }
      get <span class="Constant">:index</span>
    <span class="rubyControl">end</span>

    it { should route(<span class="Constant">:get</span>, articles_path).to(<span class="Constant">:action</span> =&gt; <span class="Constant">:index</span>) }
    it { should respond_with(<span class="Constant">:success</span>) }
    it { should render_template(<span class="Constant">:index</span>) }
    it { should_not set_the_flash }
    it { should assign_to(<span class="Constant">:articles</span>).with([<span class="Identifier">@article</span>]) }

  <span class="rubyControl">end</span>
<span class="rubyControl">end</span></pre>
<p>As you see I&#39;m a fan of <a href="http://github.com/btakita/rr/">rr</a> as well. I love the sleek and concise
syntax it offers, just as the Shoulda matchers.</p>

<p>So, now what?</p>

<p>Well, I don&#39;t like to spec views separately. It&#39;s too much of a drag to set up all the required
instance variables, because there tend to be a lot of them. That&#39;s why I use the <code>integrate_views</code>
command. I do want to spec some essential elements rendered in the view. Just knowing that no
exceptions were thrown is not always good enough.</p>

<p>The solution is the <a href="http://rubypond.com/articles/2008/03/31/using-rspec-have_tag/">have_tag</a>
matcher. This is actually a wrapper around assert_select, allowing you to use CSS selectors to check
your view. I ended up testing links to certain actions, to ensure all the actions are reachable for
the user. For example:</p>
<pre>it { should have_tag(<span class="rubyStringDelimiter">"</span><span class="String">a[href=</span><span class="rubyInterpolationDelimiter">#{</span>article_path(<span class="Identifier">@article</span>)<span class="rubyInterpolationDelimiter">}</span><span class="String">]</span><span class="rubyStringDelimiter">"</span>) }</pre>
<p>Yuck! That is a lot of noise! The whole use of RSpec is to create human readable tests. Also, there
is a lot that can go wrong here. I will easily forget one or more of those differently shaped
brackets. I want to write something like:</p>
<pre>it { should have_link_to(article_path(<span class="Identifier">@article</span>)) }</pre>
<p>Much cleaner! Making a matcher for this isn&#39;t that difficult:</p>
<pre><span class="Keyword">module</span> <span class="Type">CustomLinkMatcher</span>

  <span class="PreProc">include</span> <span class="Type">Spec</span>::<span class="Type">Rails</span>::<span class="Type">Matchers</span>

  <span class="PreProc">def</span> <span class="Function">have_link_to</span>(url)
    <span class="Type">AssertSelect</span>.new(<span class="Constant">:assert_select</span>, <span class="Constant">self</span>, <span class="rubyStringDelimiter">"</span><span class="String">a[href=</span><span class="rubyInterpolationDelimiter">#{</span>url<span class="rubyInterpolationDelimiter">}</span><span class="String">]</span><span class="rubyStringDelimiter">"</span>)
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>Don&#39;t forget to activate it, though:</p>
<pre><span class="Type">Spec</span>::<span class="Type">Runner</span>.configure <span class="rubyControl">do</span> |<span class="Identifier">config</span>|
  config.include <span class="Type">CustomLinkMatcher</span>
<span class="rubyControl">end</span></pre>
<p>So, why go through all this trouble? Why should I even care? I mean, the have_tag selector isn&#39;t
that unreadable, just a bit cluttered. Well, I found that the ease of which you can type specs is
directly related to how extensive you test. If a test is difficult to type, hard to read, or feels
repetitive, most people (with possible exception of <a href="http://smartic.us/">Bryan Liles</a> ;) ) will get
annoyed with it and don&#39;t do it anymore.</p>

<p>To give myself as an example. I never cared much about <a href="http://ruby.sadi.st/Heckle.html">heckle</a>.
Heckle could mutate so much code, I soon stopped caring. Now, with the matchers Shoulda gives me, I
like running Heckle! I know keeping Heckle happy shouldn&#39;t be a goal, and I accept certain things
Heckle will heckle me about even now, but writing specs like this really made my tests much more
robust!</p>

<p>So, in conclusion: if you find yourself hating to write certain specs, try to refactor your specs so
it becomes easy <em>and fun</em>! Try to write tests as you would like your tests to be written. Testing
should be fun! Keep it that way! Use every gem, tool and technique you have to do so!</p>
]]>
      </description>
      <guid>http://iain.nl/rspec-shoulda-and-custom-matchers</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Chainable.not.gem</title>
      <link>http://iain.nl/holidaysnothappyfalse</link>
      <pubDate>Wed, 24 Dec 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Well then: <strong>happy holidays!</strong> This x-mas, there have been a few nice Ruby presents, like
the <a href="http://rubyonrails.org/merb">merging of Rails with Merb</a> and Github <a href="http://github.com/blog/277-pages-generator">has a shiny new
feature</a> for creating project sites.</p>

<p>I too will present you a Ruby x-mas present. It&#39;s a nice, but useless present, not totally out of
line with the usual x-mas presents.</p>

<p>It is a gem called <a href="http://iain.github.com/not"><strong>not</strong></a>. With not you can get rid of exclamation
marks and the not keyword, and putting it later on in the sentence, thus making it better English.</p>

<p>An example:</p>
<pre><span class="Comment"># for core Ruby methods:</span>
<span class="Identifier">@foo</span>.not.nil?
<span class="Comment"># or any custom method:</span>
<span class="Identifier">@user</span>.not.active?
<span class="Identifier">@user</span>.not.save!</pre>
<p>If you want it, you can install it as a gem:</p>
<pre>sudo gem <span class="Statement">install</span> not</pre>
<p>or as a Rails plugin:</p>
<pre>./script/plugin <span class="Statement">install</span> git://github.com/iain/not.git</pre>
<p>I hope you&#39;ll like it! <strong>Happy holidays!</strong></p>

<h3 id="toc_0">Update</h3>

<p>I moved the gem to <a href="http://gemcutter.org">gemcutter</a>. If you haven&#39;t tumbled yet, please do so, before installing my gem:</p>
<pre>gem <span class="Statement">install</span> gemcutter
gem tumble</pre>]]>
      </description>
      <guid>http://iain.nl/holidaysnothappyfalse</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>no_value_helper plugin</title>
      <link>http://iain.nl/no_value_helper-plugin</link>
      <pubDate>Wed, 10 Dec 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>It took some late night coding, but I finished another plugin. It&#39;s a little helper that goes
by the name of <a href="http://github.com/iain/no_value_helper">no_value_helper</a>. To install it, type:
<code>.&#47;script&#47;plugin install git:&#47;&#47;github.com&#47;iain&#47;no_value_helper.git</code>. It&#39;s not that big, but fully
<a href="http://github.com/iain/no_value_helper/tree/master/spec/no_value_helper_spec.rb">tested</a>, which may
save you some time.</p>

<p>It changes:</p>
<pre><span class="PreProc">&lt;%=</span> <span class="Identifier">@user</span>.name.blank? ? <span class="rubyStringDelimiter">'</span><span class="String">no value</span><span class="rubyStringDelimiter">'</span> : h(<span class="Identifier">@user</span>.name) <span class="PreProc">%&gt;</span></pre>
<p>Into:</p>
<pre><span class="PreProc">&lt;%=</span> show(<span class="Identifier">@user</span>.name, <span class="Constant">:h</span>) <span class="PreProc">%&gt;</span></pre>
<p>But wait! There is more! This method can accept blocks too and rescue you from those pesky nils!
Keep on reading!</p>

<h3 id="toc_0">The problem I wanted to solve</h3>

<p>This Ruby on Rails plugin tries to solve a common pattern when showing
values from the database. If you want to show a nice message like &#39;no value&#39;
when an optional attribute has been left empty, you usually need to do the
same thing over and over again:</p>
<pre><span class="PreProc">&lt;%=</span> <span class="Identifier">@user</span>.name.blank? ? <span class="rubyStringDelimiter">'</span><span class="String">no value</span><span class="rubyStringDelimiter">'</span> : <span class="Identifier">@user</span>.name <span class="PreProc">%&gt;</span></pre>
<p>It gets even worse when it&#39;s about an optional relation, with some extra methods:</p>
<pre><span class="PreProc">&lt;%=</span> <span class="Identifier">@user</span>.daddy ? link_to(<span class="Identifier">@user</span>.daddy.name, <span class="Identifier">@user</span>.daddy) : <span class="rubyStringDelimiter">'</span><span class="String">no daddy</span><span class="rubyStringDelimiter">'</span> <span class="PreProc">%&gt;</span></pre>
<h3 id="toc_1">The solution: no_value_helper</h3>

<p>So this plugin tries to shorten this:</p>
<pre><span class="PreProc">&lt;%=</span> show(<span class="Identifier">@user</span>.name) <span class="PreProc">%&gt;</span></pre>
<p>Or the second example:</p>
<pre><span class="PreProc">&lt;%=</span> show(<span class="Constant">:link_to</span>, <span class="Identifier">@user</span>.daddy) { <span class="Identifier">@user</span>.daddy.name } <span class="PreProc">%&gt;</span></pre>
<p>Don&#39;t worry, NoMethodErrors will be caught for you. That is why we use a block
in this case.</p>

<p>For the exact usage, read the <a href="http://github.com/iain/no_value_helper/tree/master/spec/no_value_helper_spec.rb">specs</a>.</p>

<h3 id="toc_2">Configuration</h3>

<p>To translate the message, you can simply add the &quot;no_value&quot; key (no scope) to
your translation files.</p>
<pre><span class="Identifier">nl-NL</span><span class="Special">:</span>
  <span class="Identifier">no_value</span><span class="Special">:</span> geen waarde</pre>
<p>By default the message is encapsulated by an em-tag with the class &#39;no_value&#39;.
To change this, set the class variable <code>@@no_value_text</code> with a lambda. This is
done so I18n.translate will work. Make an initializer
(in <code>config&#47;initializers&#47;no_value_helper.rb</code>), containing this:</p>
<pre><span class="Keyword">module</span> <span class="Type">NoValueHelper</span>
  <span class="Identifier">@@no_value_text</span> = <span class="Keyword">lambda</span> { <span class="rubyStringDelimiter">"</span><span class="String">something more to your liking</span><span class="rubyStringDelimiter">"</span> }
<span class="Keyword">end</span></pre>
<p>You can also change how this plugin checks for empty values. By default this is
done with the method <a href="http://apidock.com/rails/Object/blank%3F">blank?</a>
This means that empty strings are also treated as &#39;no value&#39;. To change this,
set the class variable <code>@@no_value_check_method</code> to a lambda that does what you
want. Your initializer will look something like this:</p>
<pre><span class="Keyword">module</span> <span class="Type">NoValueHelper</span>
  <span class="Identifier">@@no_value_check_method</span> = <span class="Keyword">lambda</span> { |<span class="Identifier">value</span>| value.nil? }
<span class="Keyword">end</span></pre>
<h3 id="toc_3">Some more examples</h3>

<p>Here are some more examples to inspire you:</p>
<pre><span class="PreProc">&lt;%=</span> show(<span class="Constant">:l</span>, <span class="Constant">:format</span> =&gt; <span class="Constant">:long</span>){<span class="Identifier">@user</span>.birthday} <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%=</span> show(<span class="Identifier">@user</span>.savings, <span class="Constant">:number_to_currency</span>) <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%=</span> show(<span class="Constant">:simple_format</span>){<span class="Identifier">@user</span>.contract.company.billing_address} <span class="PreProc">%&gt;</span></pre>]]>
      </description>
      <guid>http://iain.nl/no_value_helper-plugin</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>AuthLogic is awesome!</title>
      <link>http://iain.nl/authlogic-is-awesome</link>
      <pubDate>Thu, 13 Nov 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Probably every Rails developer has used
<a href="http://github.com/technoweenie/restful-authentication">restful_authentication</a>. Most of us on
practically every application. But restful_authentication generates quite some code and is somewhat
an odd plugin. It is a bit out of place in the regular restful controllers that you make. They are
making a new <a href="http://github.com/technoweenie/restful-authentication/tree/modular">modular version</a>
of it, but it isn&#39;t much of an improvement, if you ask me.</p>

<p>Luckily, there is a new plugin&#47;gem that does this better. It&#39;s called
<a href="http://github.com/binarylogic/authlogic">AuthLogic</a>. It used to be called AuthGasm, but now we
can actually install it without blushing every time we do <code>ls vendor&#47;plugins</code>. It gives you a
familiar <code>acts_as_authentic</code> for your user model (nothing more, mind you!) and a UserSession model,
which isn&#39;t inheriting from ActiveRecord, but from AuthLogic::Session::Base class, which AuthLogic
provides.</p>

<p>The big plus is that now you can use <code>form_for</code> for user sessions just as you would for any
ActiveRecord model. Your UserSessionsController can even be like rails scaffold provides. Just save
to the @user_session object and a session is set.</p>

<p>You&#39;re free to make multiple sessions per user to be able to log in on multiple locations. Just
read the <a href="http://github.com/binarylogic/authlogic/tree/master/README.rdoc">README</a> to see what is
possible!</p>

<p>There are no specs provided with AuthLogic, so here are some helpers to spec controllers. Add them
to spec_helper.rb or in another file which gets loaded by RSpec.</p>
<pre><span class="PreProc">def</span> <span class="Function">current_user</span>(stubs = {})
  <span class="Identifier">@current_user</span> ||= mock_model(<span class="Type">User</span>, stubs)
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Function">user_session</span>(stubs = {}, user_stubs = {})
  <span class="Identifier">@current_user</span> ||= mock_model(<span class="Type">UserSession</span>, {<span class="Constant">:user</span> =&gt; current_user(user_stubs)}.merge(stubs))
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Function">login</span>(session_stubs = {}, user_stubs = {})
  <span class="Type">UserSession</span>.stub!(<span class="Constant">:find</span>).and_return(user_session(session_stubs, user_stubs))
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Function">logout</span>
  <span class="Identifier">@user_session</span> = <span class="Constant">nil</span>
<span class="PreProc">end</span></pre>
<p>So you can write specs like this:</p>
<pre>describe <span class="Type">SecretsController</span> <span class="rubyControl">do</span>
  before { login }
  it <span class="rubyStringDelimiter">"</span><span class="String">should be very very secret!</span><span class="rubyStringDelimiter">"</span>
<span class="rubyControl">end</span></pre>
<p>And as a litte bonus, it works nice with my plugin:
<a href="/acts_as_translatable_model-plugin">acts_as_translatable_model</a>. Making your login forms is easier
than ever! So please take a look at it! I&#39;m betting you&#39;ll love it!</p>
]]>
      </description>
      <guid>http://iain.nl/authlogic-is-awesome</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Asset paths</title>
      <link>http://iain.nl/asset-paths</link>
      <pubDate>Mon, 03 Nov 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Just a quickie. We all know that Rails adds asset ids to images, javascript include tags and stylesheet link tags. This is to help the browser in caching assets properly. The generated code looks something like this:</p>
<pre><span class="Keyword">&lt;</span><span class="Conditional">img</span><span class="Keyword"> </span><span class="Type">src</span><span class="Keyword">=</span><span class="String">"rails.png?20849923"</span><span class="Keyword"> </span><span class="Type">alt</span><span class="Keyword">=</span><span class="String">"Rails"</span><span class="Keyword"> /&gt;</span></pre>
<p>If I wonder if a website was made in Rails, I always look at the HTML. This is a good indicator.</p>

<p>Sometimes you don&#39;t want this behavior. It can get in the way of <code>wget</code>, which saves the file including everything after the question mark. But it&#39;s not that straightforward to turn this off. At least, I couldn&#39;t find it. There is not much information available on this subject and I had to dive into the Rails source code to solve it.</p>

<p>The easiest way I found was to override a helper method:</p>
<pre><span class="Keyword">module</span> <span class="Type">ApplicationHelper</span>
  <span class="PreProc">def</span> <span class="Function">rewrite_asset_path</span>(source)
    source
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Please correct me if there is a simpler way!</p>
]]>
      </description>
      <guid>http://iain.nl/asset-paths</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Pluralization Rails 2.2 style</title>
      <link>http://iain.nl/pluralization-rails-22-style</link>
      <pubDate>Mon, 20 Oct 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><a href="http://railscasts.com/episodes/132-helpers-outside-views">Railscast episode 132</a> talks about using
helpers outside views. All in all a good and useful screencast. I only have one comment: In Rails
2.2 internationalized pluralization goes like this:</p>
<pre><span class="Type">I18n</span>.t(<span class="Constant">:people</span>, <span class="Constant">:count</span> =&gt; <span class="Identifier">@people</span>.size)</pre>
<p>With these translation-files:</p>
<pre><span class="Identifier">en</span><span class="Special">:</span>
  <span class="Identifier">people</span><span class="Special">:</span>
    <span class="Identifier">one</span><span class="Special">:</span> <span class="String">"</span><span class="String">one person</span><span class="String">"</span>
    <span class="Identifier">other</span><span class="Special">:</span> <span class="String">"</span><span class="String">%{count} people</span><span class="String">"</span></pre><pre><span class="Identifier">nl</span><span class="Special">:</span>
  <span class="Identifier">people</span><span class="Special">:</span>
    <span class="Identifier">one</span><span class="Special">:</span> <span class="String">"</span><span class="String">een persoon</span><span class="String">"</span>
    <span class="Identifier">other</span><span class="Special">:</span> <span class="String">"</span><span class="String">%{count} personen</span><span class="String">"</span></pre>]]>
      </description>
      <guid>http://iain.nl/pluralization-rails-22-style</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Localizing Dates and Times in Rails 2.2</title>
      <link>http://iain.nl/localizing-dates-and-times-in-rails-22</link>
      <pubDate>Wed, 08 Oct 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Here is the next installment of a series of guides I&#39;m writing for internationalizing a Rails 2.2
application. Please read the first part, <a href="/translating-activerecord">Translating ActiveRecord</a>, if
you haven&#39;t already. This time I&#39;m going to talk about how to localize dates and times to a specific
language.</p>

<p>First a small recap in how to load locales. Add this to a new initializer:</p>
<pre><span class="Type">I18n</span>.load_path += <span class="Type">Dir</span>.glob(<span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">RAILS_ROOT</span><span class="rubyInterpolationDelimiter">}</span><span class="String">/app/locales/**/*.yml</span><span class="rubyStringDelimiter">"</span>)</pre>
<p>This has been changed at a very late moment. <code>I18n.store_translations</code> and <code>I18n.load_translations</code>
have been removed.</p>

<p>After that, you need to create a place to store your locales. Make the directory
<code>app&#47;locales&#47;nl-NL&#47;</code> and place your yaml files in there. Here is the English version of the
locale-file:</p>
<pre><span class="Identifier">en-US</span><span class="Special">:</span>
  <span class="Identifier">date</span><span class="Special">:</span>
    <span class="Identifier">formats</span><span class="Special">:</span>
     <span class="Comment"> # Use the strftime parameters for formats.</span>
     <span class="Comment"> # When no format has been given, it uses default.</span>
     <span class="Comment"> # You can provide other formats here if you like!</span>
      <span class="Identifier">default</span><span class="Special">:</span> <span class="String">"</span><span class="String">%Y-%m-%d</span><span class="String">"</span>
      <span class="Identifier">short</span><span class="Special">:</span> <span class="String">"</span><span class="String">%b %d</span><span class="String">"</span>
      <span class="Identifier">long</span><span class="Special">:</span> <span class="String">"</span><span class="String">%B %d, %Y</span><span class="String">"</span>

    <span class="Identifier">day_names</span><span class="Special">:</span> <span class="Special">[</span>Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday<span class="Special">]</span>
    <span class="Identifier">abbr_day_names</span><span class="Special">:</span> <span class="Special">[</span>Sun, Mon, Tue, Wed, Thu, Fri, Sat<span class="Special">]</span>

   <span class="Comment"> # Don't forget the nil at the beginning; there's no such thing as a 0th month</span>
    <span class="Identifier">month_names</span><span class="Special">:</span> <span class="Special">[</span>~, January, February, March, April, May, June, July, August, September, October, November, December<span class="Special">]</span>
    <span class="Identifier">abbr_month_names</span><span class="Special">:</span> <span class="Special">[</span>~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec<span class="Special">]</span>
   <span class="Comment"> # Used in date_select and datime_select.</span>
    <span class="Identifier">order</span><span class="Special">:</span> <span class="Special">[</span> :year, :month, :day <span class="Special">]</span>

  <span class="Identifier">time</span><span class="Special">:</span>
    <span class="Identifier">formats</span><span class="Special">:</span>
      <span class="Identifier">default</span><span class="Special">:</span> <span class="String">"</span><span class="String">%a, %d %b %Y %H:%M:%S %z</span><span class="String">"</span>
      <span class="Identifier">short</span><span class="Special">:</span> <span class="String">"</span><span class="String">%d %b %H:%M</span><span class="String">"</span>
      <span class="Identifier">long</span><span class="Special">:</span> <span class="String">"</span><span class="String">%B %d, %Y %H:%M</span><span class="String">"</span>
    <span class="Identifier">am</span><span class="Special">:</span> <span class="String">"</span><span class="String">am</span><span class="String">"</span>
    <span class="Identifier">pm</span><span class="Special">:</span> <span class="String">"</span><span class="String">pm</span><span class="String">"</span></pre>
<p>All you need to do is replace the English terms with the translated versions. Remember that all
these keys are necessary to have. If you leave out, say month_names, it won&#39;t work at all.</p>

<p>After this is done, translate dates and times like this:</p>
<pre><span class="Type">I18n</span>.localize(<span class="Type">Date</span>.today)</pre>
<p>If you want to use any of the other formats, specify this in the options hash:</p>
<pre><span class="Type">I18n</span>.localize(<span class="Type">Date</span>.today, <span class="Constant">:format</span> =&gt; <span class="Constant">:short</span>)</pre>
<p>One more tip: you can add as many formats as you like, but remember that formats like
<code>:db</code> are reserved for obvious reasons. Here is an overview of the <a href="http://www.ruby-doc.org/core/classes/Time.html#M000297">strftime syntax in
Ruby</a>.</p>

<p><strong>PS.</strong> Rails 2.2 RC1 is really really close now!</p>
]]>
      </description>
      <guid>http://iain.nl/localizing-dates-and-times-in-rails-22</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Resources</title>
      <link>http://iain.nl/resources</link>
      <pubDate>Mon, 29 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Just a simple little advice for all
<a href="http://apidock.com/rails/ActionController/Resources/resources">RESTful</a> programmers out there. It&#39;s
really simple, and cleans up your code quite a bit. A lot of Rails applications have two roles: an
admin and non admin. Your code can get pretty ugly when implementing extra features for the admin.
I&#39;m guessing everybody does this from time to time:</p>
<pre><span class="Special">-</span> <span class="rubyControl">if</span> current_user.admin?
  <span class="Special">%</span><span class="Conditional">p</span><span class="Special">=</span> link_to(<span class="Identifier">@project</span>, <span class="Constant">:method</span> =&gt; <span class="Constant">:delete</span>)
<span class="Comment">-# or this:</span>
<span class="Special">%</span><span class="Conditional">p</span><span class="Special">=</span> link_to(<span class="Identifier">@project</span>, <span class="Constant">:method</span> =&gt; <span class="Constant">:delete</span>) <span class="rubyControl">if</span> current_user.admin?</pre>
<p>It&#39;s no problem when you&#39;re doing this only once or twice, but as the project moves on, your views
get swamped, and your controllers too! My suggestion is splitting it into multiple controllers, one
for each role, like this:</p>
<pre><span class="Type">ActionController</span>::<span class="Type">Routing</span>::<span class="Type">Routes</span>.draw <span class="rubyControl">do</span> |<span class="Identifier">map</span>|
  map.resources <span class="Constant">:projects</span>
  map.resource <span class="Constant">:admin</span> <span class="rubyControl">do</span> |<span class="Identifier">a</span>|
    a.resources <span class="Constant">:projects</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">admin_projects</span><span class="rubyStringDelimiter">'</span>
  <span class="rubyControl">end</span>
<span class="rubyControl">end</span></pre>
<p>This will generate these paths (amongst all usual others):</p>
<pre>      project GET /projects/:id       { :action=>"show", :controller=>"projects"}
admin_project GET /admin/projects/:id { :action=>"show", :controller=>"admin_projects"}
</pre>
<p>This way controllers and views stay clean and uncluttered. It has a cluttered <code>rake routes</code> as trade
off though, but that&#39;s just a minor problem if you ask me. The admin controller can be used as
administrator dashboard. If you have another solution, I&#39;d love to hear it!</p>
]]>
      </description>
      <guid>http://iain.nl/resources</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>acts_as_translatable_model plugin</title>
      <link>http://iain.nl/acts_as_translatable_model-plugin</link>
      <pubDate>Mon, 22 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>After a long day in the train today, I extracted the I18n functionality from ActiveRecord so its applicable to any class. This can be especially handy if the source of the data is different, e.g. LDAP. Just install the plugin and add one line to your class to make it translatable:</p>
<pre>./script/plugin <span class="Statement">install</span> git://github.com/iain/acts_as_translatable_model</pre><pre><span class="Keyword">class</span> <span class="Type">User</span>
  acts_as_translatable_model

  <span class="Statement">attr_accessor</span> <span class="Constant">:name</span>, <span class="Constant">:password</span>
<span class="Keyword">end</span></pre>
<p>Now you can do <a href="/translating-activerecord">familiar things</a> with the class, just as you would do with normal ActiveRecord models. Supply a translation:</p>
<pre>nl<span class="Operator">-</span><span class="Identifier">NL</span><span class="Delimiter">:</span>
  <span class="Identifier">activerecord</span><span class="Delimiter">:</span>
    <span class="Identifier">models</span><span class="Delimiter">:</span>
      <span class="Identifier">user</span><span class="Delimiter">:</span> gebruiker
    <span class="Identifier">attributes</span><span class="Delimiter">:</span>
      <span class="Identifier">user</span><span class="Delimiter">:</span>
        <span class="Identifier">name</span><span class="Delimiter">:</span> naam
        <span class="Identifier">password</span><span class="Delimiter">:</span> wachtwoord</pre><pre><span class="Type">User</span>.human_name
<span class="Comment"># =&gt; "gebruiker"</span>
<span class="Type">User</span>.human_attribute_name(<span class="rubyStringDelimiter">"</span><span class="String">name</span><span class="rubyStringDelimiter">"</span>)
<span class="Comment"># =&gt; "naam"</span></pre>
<p>Of course, you can use inheritance, just as you would use Single Table Inheritance (STI).</p>

<p>It also works nicely together with <a href="/form-labels-in-rails-22">i18n_label</a>. A simple example:</p>
<pre><span class="Special">%</span><span class="Conditional">h1</span><span class="Special">=</span> translate <span class="Constant">:please_login</span>
<span class="Special">-</span> form_for(<span class="Type">User</span>.new) <span class="rubyControl">do</span> |<span class="Identifier">f</span>|
  <span class="Special">=</span> f.label <span class="Constant">:name</span>
  <span class="Special">=</span> f.text_field <span class="Constant">:name</span>
  <span class="Special">=</span> f.label <span class="Constant">:password</span>
  <span class="Special">=</span> f.password_field <span class="Constant">:password</span>
  <span class="Special">=</span> submit_tag( translate(<span class="Constant">:login</span>) )</pre>
<p>Hopefully, this will make your life a little bit easier.</p>
]]>
      </description>
      <guid>http://iain.nl/acts_as_translatable_model-plugin</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Form Labels in Rails 2.2</title>
      <link>http://iain.nl/form-labels-in-rails-22</link>
      <pubDate>Fri, 12 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Shamelessly copy-pasted from the README file of the new plugin I released today:</p>

<p>Since form labels don’t use I18n in Rails 2.2 (I was too late in submitting the patch), we’d have to
make due with a plugin.</p>

<p>Installation and configuration consists of 1 easy steps:</p>

<ul>
<li>Run: <code>.&#47;script&#47;plugin install git:&#47;&#47;github.com&#47;iain&#47;i18n_label.git</code></li>
</ul>

<h3 id="toc_0">Example</h3>

<p>In your translation file:</p>
<pre><span class="Identifier">en-US</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">attributes</span><span class="Special">:</span>
      <span class="Identifier">topic</span><span class="Special">:</span>
        <span class="Identifier">name</span><span class="Special">:</span> <span class="String">'</span><span class="String">A nice name</span><span class="String">'</span></pre>
<p>In your view:</p>
<pre><span class="PreProc">&lt;%</span> form_for <span class="Type">Topic</span>.new <span class="rubyControl">do</span> |<span class="Identifier">f</span>| <span class="PreProc">%&gt;</span>
  <span class="PreProc">&lt;%=</span> f.label <span class="Constant">:name</span> <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>The result is:</p>
<pre><span class="Keyword">&lt;</span><span class="Conditional">label</span><span class="Keyword"> </span><span class="Type">for</span><span class="Keyword">=</span><span class="String">"topic_name"</span><span class="Keyword">&gt;</span>A nice name<span class="Identifier">&lt;/</span><span class="Conditional">label</span><span class="Identifier">&gt;</span></pre>
<p>For more information about where to put your translations, read my post about <a href="/translating-activerecord">translating
ActiveRecord</a>.</p>
]]>
      </description>
      <guid>http://iain.nl/form-labels-in-rails-22</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Plugin: translatable_columns</title>
      <link>http://iain.nl/plugin-translatable_columns</link>
      <pubDate>Sat, 06 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>It was just three days ago when I discussed how to <a href="/translating-columns">translate columns</a>. At the moment I was writing it, I was already thinking: &quot;this should be a plugin&quot;. So today, I took the liberty and created it.</p>

<h3 id="toc_0">Installing</h3>

<p>First make sure you&#39;re running Rails 2.2 or edge:</p>
<pre>rake rails:freeze:edge</pre>
<p>Install the plugin:</p>
<pre>./script/plugin <span class="Statement">install</span> git://github.com/iain/translatable_columns.git</pre>
<p>Create or modify a model to have multiple columns for one attribute:</p>
<pre>./script/generate model Topic title_en:string title_nl:string title_de:string title_fr:string</pre>
<h3 id="toc_1">Usage</h3>

<p>Identify the columns you want to translate:</p>
<pre><span class="Keyword">class</span> <span class="Type">Topic</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  translatable_columns <span class="Constant">:title</span>
<span class="Keyword">end</span></pre>
<p>And you&#39;re done!</p>

<p>Create a form like this:</p>
<pre><span class="PreProc">&lt;%</span> form_for(<span class="Identifier">@topic</span>) <span class="rubyControl">do</span> |<span class="Identifier">f</span>| <span class="PreProc">%&gt;</span>
  <span class="PreProc">&lt;%=</span> f.text_field <span class="Constant">:title</span> <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>And it will save to whatever locale is set in I18n. No hard feelings, nothing to worry about.</p>

<h3 id="toc_2">Validating</h3>

<p>Validation is of course built in. If you want to validate the presence of at least one of the translations, just call <code>validates_translation_of</code>:</p>
<pre><span class="Keyword">class</span> <span class="Type">Topic</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  translatable_columns <span class="Constant">:title</span>
  validates_translation_of <span class="Constant">:title</span>
<span class="Keyword">end</span></pre>
<p>This will make your record invalid when none of the translated columns exist. It works exactly as
<code>validates_presence_of</code>, including <strong>all</strong> its options!</p>

<h3 id="toc_3">Customizing</h3>

<p>You can change the settings of translatable_columns on both a global level and at individual attribute level. There are two configuration options at the moment, called <code>full_locale</code> and <code>use_default</code>.</p>

<p>Set the global configuration in your environment file:</p>
<pre><span class="Comment"># These are the defaults of translatable_columns:</span>
<span class="Type">ActiveRecord</span>::<span class="Type">Base</span>.translatable_columns_config.full_locale = <span class="Constant">false</span>
<span class="Type">ActiveRecord</span>::<span class="Type">Base</span>.translatable_columns_config.use_default = <span class="Constant">true</span></pre>
<h4>full_locale</h4>

<p>With this option you can change which part of the locale is used in the columns. Default is
<u>false</u>, so only the first part of the locale is expected in the column. So a title for en-US
is called title_en and a title for en-GB is also called title_en. When you set <code>full_locale</code> to
<u>true</u>, it uses the entire locale, substituting the hyphen with an underscore. This way a title
for en-US is called title_en_us and a title for en-GB is called title_en_gb.</p>

<p>full_locale cannot be set per attribute just now.</p>

<h4>use_default</h4>

<p>With this option you can specify which value will be returned automatically if no proper value has
been found. Default is <u>true</u>, so it will try harder to find a value. It might even be a value
in another language.</p>

<p>You can set this option per attribute if you&#39;d like, to override the global config.</p>
<pre><span class="Keyword">class</span> <span class="Type">Topic</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  translatable_columns <span class="Constant">:title</span>, <span class="Constant">:use_default</span> =&gt; <span class="Constant">false</span>
<span class="Keyword">end</span></pre>
<h3 id="toc_4">Some extras</h3>

<p>What if the user has selected a locale which you don&#39;t have in the database? In this case it&#39;ll
get the column belonging to the I18n.default_locale. Make sure you have a column for this locale,
because you&#39;ll be serving a nasty error if even this one isn&#39;t present!</p>

<p>You might want to provide multiple languages for a user to fill in at once. This is one way to do it:</p>
<pre><span class="PreProc">&lt;%</span> form_for(<span class="Identifier">@topic</span>) <span class="rubyControl">do</span> |<span class="Identifier">f</span>| <span class="PreProc">%&gt;</span>
  <span class="PreProc">&lt;%</span> <span class="Type">Topic</span>.available_translatable_columns_of(<span class="Constant">:title</span>).each <span class="rubyControl">do</span> |<span class="Identifier">attribute</span>| <span class="PreProc">%&gt;</span>
    <span class="PreProc">&lt;%=</span> f.text_field attribute <span class="PreProc">%&gt;</span>
  <span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>Happy devving!</p>
]]>
      </description>
      <guid>http://iain.nl/plugin-translatable_columns</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>The Future of I18n in Ruby on Rails @ RailsConf</title>
      <link>http://iain.nl/the-future-of-i18n-in-ruby-on-rails-railsconf</link>
      <pubDate>Sat, 06 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Sven Fuchs put his presentation of <a href="http://www.artweb-design.de/2008/9/6/the-future-of-i18n-in-ruby-on-rails-railsconf-europe-2008">i18n in Ruby on Rails online</a>. A fine presentation! A must read for every Rails developer!</p>
]]>
      </description>
      <guid>http://iain.nl/the-future-of-i18n-in-ruby-on-rails-railsconf</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>My 5 minutes of fame @ RailsConf</title>
      <link>http://iain.nl/my-5-minutes-of-fame-railsconf</link>
      <pubDate>Thu, 04 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><a href="http://workingwithrails.com/person/9963-sven-fuchs">Sven Fuchs</a> gave a presentation of Rails i18n today. And I was in the &#39;thank you&#39; page! :)</p>

<figure class="ir_black"><img title="rails-i18n-presentation" src="/cam.jpg" alt="I am thanked" width="500" height="375"></figure>

<p>Nice to see that Sven also thanked himself :)</p>
]]>
      </description>
      <guid>http://iain.nl/my-5-minutes-of-fame-railsconf</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Translating Columns</title>
      <link>http://iain.nl/translating-columns</link>
      <pubDate>Wed, 03 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>I made this into a plugin: <a href="/plugin-translatable_columns">translatable_columns</a>.</strong></p>

<p>Dmitry <a href="/translating-activerecord#comment-96">asked in the comments</a> of my last post <a href="/translating-activerecord">about translating ActiveRecord</a>:</p>

<blockquote>
<p>Can you write about how to use translated columns of database in rails? For example we have table
named ‘blog’, and I want to translate it on several languages: fr, en, ru. How to do that?</p>
</blockquote>

<p>And although I don&#39;t think this is the way to go, I can of course demonstrate an easy way to do
this, using I18n.</p>

<p>Here&#39;s the table definition:</p>
<pre>create_table <span class="Constant">:posts</span> <span class="rubyControl">do</span> |<span class="Identifier">t</span>|
  t.string <span class="Constant">:title_en</span>, <span class="Constant">:title_nl</span>, <span class="Constant">:title_fr</span>, <span class="Constant">:title_de</span>
  t.string <span class="Constant">:text_en</span>, <span class="Constant">:text_nl</span>, <span class="Constant">:text_fr</span>, <span class="Constant">:text_de</span>
<span class="rubyControl">end</span></pre>
<p>So what you&#39;d want to do is read the currently selected locale and choose to write to the proper attribute depending on that.</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  <span class="PreProc">def</span> <span class="Function">title</span>
    <span class="Constant">self</span>[column(<span class="rubyStringDelimiter">'</span><span class="String">title</span><span class="rubyStringDelimiter">'</span>)]
  <span class="PreProc">end</span>
  <span class="PreProc">def</span> <span class="Function">title=</span>(str)
    <span class="Constant">self</span>[column(<span class="rubyStringDelimiter">'</span><span class="String">title</span><span class="rubyStringDelimiter">'</span>)] = str
  <span class="PreProc">end</span>
<span class="Statement">private</span>
  <span class="PreProc">def</span> <span class="Function">column</span>(name)
    column_name = <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span>name<span class="rubyInterpolationDelimiter">}</span><span class="String">_</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">I18n</span>.locale.split(<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).first<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
    <span class="Constant">self</span>.class.column_names.include?(column_name) ? column_name.to_sym : <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span>name<span class="rubyInterpolationDelimiter">}</span><span class="String">_</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">I18n</span>.default_locale.split(<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).first.to_sym<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Now, you can treat Post as if it had a normal title attribute, but it would save to the proper
column. If you don&#39;t have a column named for this attribute, it&#39;ll save or get the value of the
default_locale.</p>

<p>So for instance you can do this in your edit view:</p>
<pre><span class="PreProc">&lt;%</span> form_for(<span class="Identifier">@post</span>) <span class="rubyControl">do</span> |<span class="Identifier">f</span>| <span class="PreProc">%&gt;</span>
  <span class="PreProc">&lt;%=</span> f.text_field <span class="Constant">:title</span> <span class="PreProc">%&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>But when you have multiple columns that needs to be translated, even scattered through multiple
models, it tends to be a boring and repeating business to add all those virtual attributes. So let&#39;s
do some meta-programming, and clean up models!</p>

<p>First, make a file in the <code>RAILS_ROOT&#47;lib</code> directory, called <code>load_translations.rb</code> and put in this
Ruby meta-programming goodness&#47;madness:</p>
<pre><span class="Keyword">module</span> <span class="Type">TranslatableColumns</span>

  <span class="PreProc">def</span> <span class="Function">translatable_columns</span>(*columns)
    columns.each <span class="rubyControl">do</span> |<span class="Identifier">column</span>|

      define_method column <span class="rubyControl">do</span>
        <span class="Constant">self</span>[<span class="Constant">self</span>.class.column_translated(column)]
      <span class="rubyControl">end</span>

      define_method <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span>column<span class="rubyInterpolationDelimiter">}</span><span class="String">=</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span> |<span class="Identifier">value</span>|
        <span class="Constant">self</span>[<span class="Constant">self</span>.class.column_translated(column)] = value
      <span class="rubyControl">end</span>

    <span class="rubyControl">end</span>
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">column_translated</span>(name)
    column_name = <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span>name<span class="rubyInterpolationDelimiter">}</span><span class="String">_</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">I18n</span>.locale.split(<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).first<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
    <span class="Constant">self</span>.column_names.include?(column_name) ? column_name.to_sym : <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span>name<span class="rubyInterpolationDelimiter">}</span><span class="String">_</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">I18n</span>.default_locale.split(<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).first.to_sym<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>Now all you have to to in the model is extend it with this module and specify which columns can be
translated:</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  <span class="PreProc">extend</span> <span class="Type">TranslatableColumns</span>
  translatable_columns <span class="Constant">:title</span>, <span class="Constant">:text</span>
<span class="Keyword">end</span></pre>
<p>Still I&#39;m not really fond of this. I can&#39;t find a good, sensible scenario where this would be the
best option. I would rather go with an attribute called &#39;locale&#39;. So let&#39;s look at that too.</p>
<pre>./script/generate migration add_locale_to_post locale:string
rake db:migrate</pre>
<p>And add a named_scope to the models you want to be localized, like Post in this case, to get the
proper locales and save it to whatever locale was selected at the moment, if it hasn&#39;t already been
set any other way (you might want to make the user able to choose it when entering the post).</p>
<pre><span class="Keyword">class</span> <span class="Type">Post</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  named_scope <span class="Constant">:localized</span>, { <span class="Constant">:conditions</span> =&gt; { <span class="Constant">:locale</span> =&gt; <span class="Type">I18n</span>.locale } } }
  before_save <span class="Constant">:store_locale</span>
<span class="Statement">private</span>
  <span class="PreProc">def</span> <span class="Function">store_locale</span>
    <span class="Constant">self</span>[<span class="Constant">:locale</span>] ||= <span class="Type">I18n</span>.locale
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>Let&#39;s meta-program this one as well!</p>

<p>Get the proper posts, just call <code>Post.localized</code> or <code>Post.localized.find(params[:id])</code>. Note that
I&#39;m not using any translatable columns now. Just use normal columns and create multiple posts if you
want more than one language for a post (e.g. create a Dutch one and a French one).</p>

<p>As you can see, I&#39;m not using the translating functionality of I18n here. I just use I18n to know
which locale to choose.</p>
]]>
      </description>
      <guid>http://iain.nl/translating-columns</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Translating ActiveRecord</title>
      <link>http://iain.nl/translating-activerecord</link>
      <pubDate>Mon, 01 Sep 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>Updated October 10th, 2008 to be up to date with Rails 2.2 RC1 release.</strong></p>

<p>With Rails 2.2 releasing any day now, I want to show you how to translate ActiveRecord related
stuff. It is quite easy, once you know where to keep your translations. Here is a complete guide to
using all built in translation methods!</p>

<h3 id="toc_0">Scenario</h3>

<p>Suppose we&#39;re building a forum. A forum has several types (e.g. admin) of users and suppose we want
to make the most important users into separate models using Single Table Inheritance (sti). This
gives us the most complete scenario in showing off all translations:</p>
<pre><span class="Keyword">class</span> <span class="Type">User</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  validates_presence_of <span class="Constant">:name</span>, <span class="Constant">:email</span>, <span class="Constant">:encrypted_password</span>, <span class="Constant">:salt</span>
  validates_uniqueness_of <span class="Constant">:email</span>, <span class="Constant">:message</span> =&gt; <span class="Constant">:already_registered</span>
<span class="Keyword">end</span>

<span class="Keyword">class</span> <span class="Type">Admin</span> &lt; <span class="Type">User</span>
  validate <span class="Constant">:only_men_can_be_admin</span>
<span class="Statement">private</span>
  <span class="PreProc">def</span> <span class="Function">only_men_can_be_admin</span>
    errors.add(<span class="Constant">:gender</span>, <span class="Constant">:chauvinistic</span>, <span class="Constant">:default</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">This is a chauvinistic error message</span><span class="rubyStringDelimiter">"</span>) <span class="Conditional">unless</span> gender == <span class="rubyStringDelimiter">'</span><span class="String">m</span><span class="rubyStringDelimiter">'</span>
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<h3 id="toc_1">Setting up</h3>

<p>Make sure you&#39;re running Rails 2.2 or Rails edge (<code>rake rails:freeze:edge</code>)</p>

<p>Now let&#39;s translate all this into <a href="http://icanhascheezburger.com">LOLCAT</a>, just for fun. We need a
directory to place the locale files:</p>
<pre><span class="Statement">mkdir</span> app/locales</pre>
<p>And we need to load all files as soon as the application starts. So we make an initializer:</p>
<pre><span class="Comment"># config/initializers/load_translations.rb</span>
<span class="rubyStringDelimiter">%w{</span><span class="String">yml rb</span><span class="rubyStringDelimiter">}</span>.each <span class="rubyControl">do</span> |<span class="Identifier">type</span>|
  <span class="Type">I18n</span>.load_path += <span class="Type">Dir</span>.glob(<span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">RAILS_ROOT</span><span class="rubyInterpolationDelimiter">}</span><span class="String">/app/locales/**/*.</span><span class="rubyInterpolationDelimiter">#{</span>type<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">"</span>)
<span class="rubyControl">end</span>
<span class="Type">I18n</span>.default_locale = <span class="rubyStringDelimiter">'</span><span class="String">LOL</span><span class="rubyStringDelimiter">'</span></pre>
<p>This approach is recommended, because loading files is not something you want to do during the
request, when it should already be available. Setting you&#39;re locale like this is probably not
recommended, but it&#39;s easy, if you&#39;re just using one language.</p>

<h3 id="toc_2">Translating models</h3>

<p>Next, we&#39;re going to make some simple translation files. All ActiveRecord translations need to be in
the activerecord scope. So when starting your locale file, it starts with the locale name, followed
by the scope.</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">models</span><span class="Special">:</span>
      <span class="Identifier">user</span><span class="Special">:</span> kitteh
      <span class="Identifier">admin</span><span class="Special">:</span> Ceiling cat</pre>
<p>Let&#39;s try this out in <code>script&#47;console</code></p>
<pre><span class="Type">User</span>.human_name
<span class="Comment"># =&gt; "kitteh"</span>
<span class="Type">Admin</span>.human_name
<span class="Comment"># =&gt; "Ceiling cat"</span></pre>
<p>It&#39;s nice to know that the method <code>human_name</code> is used by error messages in validations too. But
we&#39;ll come to that in just a second.</p>

<p>If you didn&#39;t specify the translation of admin, it would have used the translation of user, because it inherited it.</p>

<h3 id="toc_3">Translating attributes</h3>

<p>We could append to the same file, but I choose to make a new file, because it keeps this post clean
and it&#39;s a bit easier to see how the scoping works.</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">attributes</span><span class="Special">:</span>
      <span class="Identifier">user</span><span class="Special">:</span>
        <span class="Identifier">name</span><span class="Special">:</span> naem
        <span class="Identifier">email</span><span class="Special">:</span> emale</pre>
<p>And let&#39;s try this again:</p>
<pre><span class="Type">User</span>.human_attribute_name(<span class="rubyStringDelimiter">"</span><span class="String">name</span><span class="rubyStringDelimiter">"</span>)
<span class="Comment"># =&gt; "naem"</span>
<span class="Type">Admin</span>.human_attribute_name(<span class="rubyStringDelimiter">"</span><span class="String">email</span><span class="rubyStringDelimiter">"</span>)
<span class="Comment"># =&gt; "emale"</span></pre>
<p>Once again, you can see that single table inheritance helps us with this.</p>

<p>Both human_name and human_attribute cannot really fail, because if no translation has been
specified, it would return the normal humanized version. So if you&#39;re making an English site, you
don&#39;t really need to translate models and attributes.</p>

<h3 id="toc_4">Translating default validations</h3>

<p>Let&#39;s translate a few default messages:</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">errors</span><span class="Special">:</span>
      <span class="Identifier">messages</span><span class="Special">:</span>
        <span class="Identifier">blank</span><span class="Special">:</span> <span class="String">"</span><span class="String">can not has nottin</span><span class="String">"</span></pre><pre>u = <span class="Type">User</span>.new
<span class="Comment"># =&gt; #&lt;User id: nil, etc&gt;</span>
u.valid?
<span class="Comment"># =&gt; false</span>
u.errors.on(<span class="Constant">:name</span>)
<span class="Comment"># =&gt; "can not has nottin"</span></pre>
<h3 id="toc_5">Interpolation in validations</h3>

<p>You have more freedom in your validation messages now. With every message you can interpolate the
translated name of the model, the attribute and the value. The variable &#39;count&#39; is also available
where applicable (e.g. <code>validates_length_of</code>)</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">errors</span><span class="Special">:</span>
      <span class="Identifier">messages</span><span class="Special">:</span>
        <span class="Identifier">already_registered</span><span class="Special">:</span> <span class="String">"</span><span class="String">u already is {{model}}</span><span class="String">"</span></pre><pre>u.errors.on(<span class="Constant">:email</span>)
<span class="Comment"># =&gt; "u already is kitteh"</span></pre>
<p>Remember to put quotes around the translation key in yaml, because it&#39;ll fail without it, when using
the interpolation brackets.</p>

<h3 id="toc_6">Model specific messages</h3>

<p>A message specified in the activerecord.errors.models scope overrides the translation of this kind
of message for the entire model.</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">errors</span><span class="Special">:</span>
      <span class="Identifier">messages</span><span class="Special">:</span>
        <span class="Identifier">blank</span><span class="Special">:</span> <span class="String">"</span><span class="String">can not has nottin</span><span class="String">"</span>
      <span class="Identifier">models</span><span class="Special">:</span>
        <span class="Identifier">admin</span><span class="Special">:</span>
          <span class="Identifier">blank</span><span class="Special">:</span> <span class="String">"</span><span class="String">want!</span><span class="String">"</span></pre><pre>u.errors.on(<span class="Constant">:name</span>)
<span class="Comment"># =&gt; "can has nottin"</span>
a = <span class="Type">Admin</span>.new
<span class="Comment"># =&gt; #&lt;Admin id: nil, etc&gt;</span>
a.valid?
<span class="Comment"># =&gt; false</span>
a.errors.on(<span class="Constant">:salt</span>)
<span class="Comment"># =&gt; "want!"</span></pre>
<h3 id="toc_7">Attribute specific messages</h3>

<p>Any translation in the activerecord.errors.models.model_name.attributes scope overrides model
specific attribute- and default messages.</p>
<pre><span class="Identifier">LOL</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">errors</span><span class="Special">:</span>
      <span class="Identifier">models</span><span class="Special">:</span>
        <span class="Identifier">admin</span><span class="Special">:</span>
          <span class="Identifier">blank</span><span class="Special">:</span> <span class="String">"</span><span class="String">want!</span><span class="String">"</span>
          <span class="Identifier">attributes</span><span class="Special">:</span>
            <span class="Identifier">salt</span><span class="Special">:</span>
              <span class="Identifier">blank</span><span class="Special">:</span> <span class="String">"</span><span class="String">is needed for cheezburger</span><span class="String">"</span></pre><pre>a.errors.on(<span class="Constant">:name</span>)
<span class="Comment"># =&gt; "want!"</span>
a.errors.on(<span class="Constant">:salt</span>)
<span class="Comment"># =&gt; "is needed for cheezburger"</span></pre>
<h3 id="toc_8">Defaults</h3>

<p>When you specify a symbol as the default option, it will be translated like a normal error message,
just like you&#39;ve seen with <code>:already_registered</code>. When default hasn&#39;t been found, it&#39;ll try looking
up the normal key you have given. With <code>:already_registered</code>, that key has already been set by
Rails, because we&#39;re using <code>validates_uniqueness_of</code>.</p>

<p>When you specify a string as default value, it&#39;ll use this when no translations have otherwise been
found.</p>
<pre>a.gender = <span class="rubyStringDelimiter">'</span><span class="String">f</span><span class="rubyStringDelimiter">'</span>
<span class="Comment"># =&gt; "f"</span>
a.valid?
<span class="Comment"># =&gt; false</span>
a.errors.on(<span class="Constant">:gender</span>)
<span class="Comment"># =&gt; "This is a chauvinistic error message"</span></pre>
<h3 id="toc_9">Using error_messages_for</h3>

<p>When you want to display the error messages in a model in a view, most people will user
error_messages_for. These messages are also translated. The message has a header and a single line,
saying how many errors there are. Here are the default English translations of these messages. I
will leave it up to you to translate it to LOLCAT. Win a lifetime supply of cheezburgerz* with this
mini-competition ;)</p>
<pre><span class="Identifier">en-US</span><span class="Special">:</span>
  <span class="Identifier">activerecord</span><span class="Special">:</span>
    <span class="Identifier">errors</span><span class="Special">:</span>
      <span class="Identifier">template</span><span class="Special">:</span>
        <span class="Identifier">header</span><span class="Special">:</span>
          <span class="Identifier">one</span><span class="Special">:</span> <span class="String">"</span><span class="String">1 error prohibited this {{model}} from being saved</span><span class="String">"</span>
          <span class="Identifier">other</span><span class="Special">:</span> <span class="String">"</span><span class="String">{{count}} errors prohibited this {{model}} from being saved</span><span class="String">"</span>
        <span class="Identifier">body</span><span class="Special">:</span> <span class="String">"</span><span class="String">There were problems with the following fields:</span><span class="String">"</span></pre>
<p>There is one slight problem with the messages it displays. <code>error_messages_for</code> uses the
<code>errors.full_messages</code> in it&#39;s list. This means that the attribute names will be put before it. Of
course these will be translated with <code>human_attribute_name</code>, but it might not always be desirable.
In other languages than English it&#39;s sometimes hard to formulate a nice error message with the
attribute name at the beginning. This will have to be fixed in later Rails versions.</p>

<h3 id="toc_10">Conclusion</h3>

<p>I hope you&#39;ll agree with me that these translation options for ActiveRecord are really nice! This
is what we have been waiting for. Too bad I was a bit too late with my adjustments, so form labels
don&#39;t translate by default. I did build it, but Rails was already feature frozen by then. I will
probably post a plugin that adds this functionality. Same goes for a i18n version of scaffold.</p>

<p>Please keep coming back to my site, or add the RSS feed to your favorite reader.</p>

<p>Of course, stay in touch with the <a href="http://groups.google.com/group/rails-i18n">i18n mailinglist</a>. A
lot of people are putting a lot of effort into the project. New plugins and gems solving problems
problems rapidly. I18n is one of the more difficult things to do, so if you have a special insight
in a language, please contribute!</p>

<p><strong>Happy devving!</strong></p>

<p>PS. Damn! I wish I was in <a href="http://en.oreilly.com/railseurope2008/public/content/home">Berlin</a> right now!</p>

<p style="font-size: 40%">* invisible cheezburgerz only</p>

<h3 id="toc_11">Update</h3>

<p>This post is old. Still, after 2 years, it still accounts for 10% of my daily traffic. How cool is
that? Seriously though, read the <a href="http://guides.rubyonrails.org/i18n.html">official Rails guide</a> on
this subject, for up to date information!</p>
]]>
      </description>
      <guid>http://iain.nl/translating-activerecord</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>i18n and l10n on r9r 2.2</title>
      <link>http://iain.nl/i18n-and-l10n-on-r9r-2-2</link>
      <pubDate>Sat, 16 Aug 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>Updated at October 10th 2008 to be up to date with Rails 2.2 RC1</strong></p>

<p>Ruby on Rails (r9r ;) ) v2.2 ships with builtin internationalization (i18n). It tries to solve the
problem dividing the world: language and localization (l10n). This topic is the most annoying of
most topics in programming. Anyone who has ever worked with dates, timezones and number formatting
has probably been swearing at it, loosing sleep over it and cursing the fact that difference exist
between cultures. The idiot that made this decision <em>&quot;I know that they use a comma as delimiter in
country X, but in my country we&#39;re going to use a dot!&quot;</em> certainly deserves to be shot, if he (or
she) hasn&#39;t already died. And whoever thought of the ridiculous way in how we measure time? Dates
and times really suck!</p>

<p>There are two kinds of problems here. If you live in a country other than the US, preferably one
where they don&#39;t speak English, and want to make a website, you&#39;re immediately fucked. If you are
from any English speaking country, or just don&#39;t care yet, the problem will arise a bit later when
you&#39;re expanding beyond the borders.</p>

<p>Making your site in just 1 language is relatively easy. Before Rails 2.2 we had to rely on a lot of
<a href="http://agilewebdevelopment.com/plugins/dutchify">monkeypatching</a>, overriding some key parts of the
framework. But not anymore. In Rails 2.2, only two lines will fix the problem.</p>
<pre><span class="Type">I18n</span>.locale = <span class="rubyStringDelimiter">'</span><span class="String">nl-NL</span><span class="rubyStringDelimiter">'</span>
<span class="Type">I18n</span>.load_path &lt;&lt; <span class="rubyStringDelimiter">"</span><span class="rubyInterpolationDelimiter">#{</span><span class="Type">RAILS_ROOT</span><span class="rubyInterpolationDelimiter">}</span><span class="String">/config/translations.yml</span><span class="rubyStringDelimiter">"</span></pre>
<p>Put them somewhere they&#39;ll get loaded, an
<a href="http://ryandaigle.com/articles/2007/2/23/what-s-new-in-edge-rails-stop-littering-your-%0Aevnrionment-rb-with-custom-initializations">initializer</a> will do. All you need to do now is to make you&#39;re basic
Rails translations for you language. Does your language use a dot or a comma, what does &quot;invalid&quot;
mean in your language, etc.</p>

<p>Having multiple translations at once, were the user can choose the language they prefer, is a bit
more difficult. You have to find out which language they have chosen and load the proper translation
file every time a new request comes in. The best way to do this is make a before_filter in your
application controller. In here you find out what the language is, and load the appropriate file.</p>
<pre><span class="Keyword">class</span> <span class="Type">ApplicationController</span> &lt; <span class="Type">ActionController</span>::<span class="Type">Base</span>
  before_filter <span class="Constant">:set_locale</span>
  <span class="Statement">private</span>
  <span class="PreProc">def</span> <span class="Function">set_locale</span>
    <span class="Type">I18n</span>.locale = params[<span class="Constant">:locale</span>] <span class="rubyControl">or</span> session[<span class="Constant">:locale</span>] <span class="rubyControl">or</span> <span class="Type">I18n</span>.default_locale
  <span class="PreProc">end</span>
<span class="Keyword">end</span></pre>
<p>How to make translation files is the topic of my next post, so stay tuned! Stay updated through the
<a href="http://groups.google.com/group/rails-i18n/">mailinglist</a> too! For now, things are still changing
rapidly, so please take care. When Rails 2.2 ships (hopefully somewhere next month), it&#39;ll be safe!</p>
]]>
      </description>
      <guid>http://iain.nl/i18n-and-l10n-on-r9r-2-2</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Finally! Rails goes i18n!</title>
      <link>http://iain.nl/finally-rails-goes-i18n</link>
      <pubDate>Fri, 08 Aug 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>It has been some time, I know. It was a busy time. Since my last post I started working at <a href="http://finalist.com/">Finalist
IT Group</a>, an exciting company doing exciting projects. Right now I&#39;m doing a
very demanding project for Eindhoven city council, which is quite far away from my home (well, in
Holland it is anyway).</p>

<p>But time hasn&#39;t stopped. Ruby on Rails is busy advancing to version 2.2. One new feature in the
upcoming Rails version has caught my eye and my undivided love and attention. It&#39;s the I18n-module
built into Rails! It is already available if you&#39;re running edge.</p>

<p>Rails 2.2 ships with it&#39;s language elements already indexed and a simple backend (called
SimpleBackend) for handling translations. The whole idea is to keep it as simple as possible so
any developer can implement their own way of doing the i18n-dance. The SimpleBackend keeps it
translations in memory. Soon a new version of Globalize will arrive for storing translation in a
database and no doubt a gettext based backend will appear soon too.</p>

<p>Using the SimpleBackend, translating your database is dead easy. Amongst it&#39;s features are (in no
particular order):</p>

<ul>
<li>Scoping, for sorting your keys and thus avoiding name clashes</li>
<li>Bulk look up of multiple translations</li>
<li>Default translations for when the translation hasn&#39;t been found</li>
<li>Interpolation, inserting values in the middle of translations</li>
<li>Pluralization, handling multiple translations depending on a value being plural or singular</li>
<li>Having multiple default translation, for using another keys as default</li>
<li>Localization of dates and times</li>
</ul>

<p>I can&#39;t go into each features into one post, so I&#39;ll be posting more in a while. First, let us take
a look at the basics:</p>
<pre><span class="Type">I18n</span>.store_translations( <span class="rubyStringDelimiter">'</span><span class="String">en-US</span><span class="rubyStringDelimiter">'</span>, { <span class="Constant">:hello</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">hello</span><span class="rubyStringDelimiter">'</span> } )
<span class="Type">I18n</span>.store_translations( <span class="rubyStringDelimiter">'</span><span class="String">nl-NL</span><span class="rubyStringDelimiter">'</span>, { <span class="Constant">:hello</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">hallo</span><span class="rubyStringDelimiter">'</span> } )
<span class="Type">I18n</span>.translate( <span class="Constant">:hello</span> ) <span class="Comment"># =&gt; "hello" (en-US is the default locale)</span>
<span class="Type">I18n</span>.locale = <span class="rubyStringDelimiter">'</span><span class="String">nl-NL</span><span class="rubyStringDelimiter">'</span>
<span class="Type">I18n</span>.translate( <span class="Constant">:hello</span> ) <span class="Comment"># =&gt; "hallo"</span></pre>
<p>The big advantage is that I18n is now baked into Rails, so all you&#39;re favorite &quot;railties&quot; will
automagically be translated (en-US translations are of course default and provided for, so you don&#39;t
have to use I18n if you don&#39;t want to). Amongst others, cool stuff like date-formats, number and
currency formatting and default ActiveRecord error messages are indexed. Here is an example:</p>
<pre><span class="Type">I18n</span>.store_translations( <span class="rubyStringDelimiter">'</span><span class="String">nl-NL</span><span class="rubyStringDelimiter">'</span>, { <span class="Constant">:support</span> =&gt; { <span class="Constant">:array</span> =&gt; { <span class="Constant">:sentence_connector</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">en</span><span class="rubyStringDelimiter">'</span> } } } )
<span class="rubyStringDelimiter">%w{</span><span class="String">a b c</span><span class="rubyStringDelimiter">}</span>.to_sentence <span class="Comment"># =&gt; "a, b, en c" (look mama, no I18n.translate call!)</span></pre>
<p>In date(and -time) objects you need to call the method localize to translate. You can define your
own preferred formats too, so no more need for those ugly strftime method calls in your code.</p>
<pre><span class="Type">I18n</span>.localize( <span class="Type">Time</span>.now, <span class="Constant">:format</span> =&gt; <span class="Constant">:long</span> ) <span class="Comment"># "vrijdag, 8 augustus 2008, 20:51:15"</span></pre>
<p>ActiveRecord column names and error messages are easily translated too! You just have to know the
proper scope. What you need to do is store translations in these scopes and Rails will automatically
use it for you. In my opinion it is a bit of mess. Hopefully it&#39;ll be changed to something less
scattered soon.</p>

<p>In this example, I have a model called Post and it has an attribute named &#39;title&#39;.</p>

<h3 id="toc_0">Update 1</h3>

<p>The proper way to translate ActiveRecord is described <a href="/translating-activerecord">here!</a></p>
<pre><span class="Type">I18n</span>.store_translations( <span class="rubyStringDelimiter">'</span><span class="String">en-US</span><span class="rubyStringDelimiter">'</span>, {
  <span class="Constant">:active_record</span> =&gt; {
    <span class="Constant">:error</span> =&gt; {
      <span class="Constant">:header_message</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">default message for error_messages_for</span><span class="rubyStringDelimiter">"</span>,
      <span class="Constant">:post</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">When the model name is not what you like</span><span class="rubyStringDelimiter">"</span>
    },
    <span class="Constant">:error_messages</span> =&gt; {
      <span class="Constant">:blank</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">your default 'cannot be blank' message</span><span class="rubyStringDelimiter">"</span>,
      <span class="Constant">:custom</span> =&gt; {
        <span class="Constant">:post</span> =&gt; {
          <span class="Constant">:title</span> =&gt; {
            <span class="Constant">:blank</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">error message for @post.title only</span><span class="rubyStringDelimiter">"</span>
          }
        }
      }
    },
    <span class="Constant">:human_attribute_names</span> =&gt; {
      <span class="Constant">:post</span> =&gt; {
        <span class="Constant">:title</span> =&gt; <span class="rubyStringDelimiter">"</span><span class="String">Translation of the column name</span><span class="rubyStringDelimiter">"</span>
      }
    }
  }
} )
<span class="Type">I18n</span>.translate <span class="Constant">:'active_record.human_attribute_names.post.title'</span>
<span class="Comment"># =&gt; "Translation of the column name"</span></pre>
<p>Unfortunately there isn&#39;t a good list of which translations are available. I will try to make one
soon.</p>

<p>There are some limitations to the default I18n implementation. How you want to incorporate it in
your site is completely up to you. Also, how and where you keep your translations has not been
implemented. So you have to load a bunch of files yourself in which you keep translations.</p>

<p>But it gets easier. I made a plugin, called <a href="http://github.com/iain/i18n_yaml/">i18n_yaml</a>,
which handles all of this for you. It is not a different backend, but rather an extension to
SimpleBackend. It stores its translation files in yaml-files found in app&#47;locales. It also provides
a before_filter to find the appropriate locale. In other words: everything you need to make
SimpleBackend useful! Like Rails 2.2, it is not finished yet, but you can have a go at it of course.</p>

<p>Would you like to contribute to i18n? Join the
<a href="http://groups.google.com/group/rails-i18n">mailinglist</a>. Rails i18n also launched it&#39;s own website:
<a href="http://rails-i18n.org/">rails-i18n.org</a>. There are a number of tutorials and articles already
available, listed <a href="http://rails-i18n.org/wiki">here</a>.</p>

<p>This concludes the first part of the Rails i18n introduction. I&#39;ll be posting some more insights
into i18n soon, so stay tuned!</p>

<h3 id="toc_1">Update 2</h3>

<p>Locate the locale.yml files in Rails to find all possible translations. Here is <a href="http://pastie.org/306532">a
pastie</a> with everything translated to Dutch.</p>
]]>
      </description>
      <guid>http://iain.nl/finally-rails-goes-i18n</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Bringing Objects To Views</title>
      <link>http://iain.nl/bringing-objects-to-views</link>
      <pubDate>Sat, 26 Apr 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Ruby on Rails is a fine framework. It uses Ruby which is beautiful programming language. Everything is an object in Ruby, and the <a href="http://poignantguide.net/ruby/chapter-4.html#section4">block structure</a> allows you to do marvelous stuff with it. The Rails team is well aware of this and uses it, making Rails a great partner in crime. I still remember the first time I viewed the migration for creating a new database table:</p>
<pre>create_table <span class="rubyStringDelimiter">"</span><span class="String">users</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span> |<span class="Identifier">t</span>|
  t.column <span class="Constant">:name</span>, <span class="Constant">:string</span>, <span class="Constant">:limit</span> =&gt; <span class="Number">40</span>
  t.column <span class="Constant">:email</span>, <span class="Constant">:string</span>
  <span class="Comment"># etc</span>
<span class="rubyControl">end</span></pre>
<p>I almost didn&#39;t recognize it at first. I didn&#39;t know Ruby back then, I just did what was necessary to make it work without looking at what it does. But take a good look at what it really does. It creates a table and gives you an object for you to play with. Within the block you can edit the properties of the thing you&#39;re creating in small readable lines. Ruby itself is full of these functions. Iterators are probably the best examples. What would any Ruby programmer do without <tt><a href="http://www.ruby-doc.org/core/classes/Hash.html#M002889">each</a></tt>, <tt><a href="http://www.ruby-doc.org/core/classes/Hash.html#M002900">select</a></tt> and <tt><a href="http://www.ruby-doc.org/core/classes/Hash.html#M002893">sort</a></tt>? These blocks are arguably one of the nicest features in Ruby.</p>

<p>It&#39;s good to know that Rails incorporates this feature. Although I find it lacking in the view part. Sure you&#39;ll use methods like <code>each</code>, but think of all the helper-methods out there. Usually they are single methods doing some stuff and returning some HTML. Nice, but a bit cumbersome. Not that you&#39;d need anything more complicated for creating a link or an image, but there is hardly anything &#39;sweet&#39; going on in the views.</p>

<p>Then there are forms. Forms form the center of any web application, certainly Rails-made applications. In the views at least. Rails gives us the <tt><a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html#M000920">form_for</a></tt> and <tt><a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormTagHelper.html#M001036">form_tag</a></tt> methods. These work in rather the same way as the migrations, giving you an form-object to play with. With this form object you can create all kinds of fields. Consider this simple form:</p>
<pre><span class="PreProc">&lt;%</span> form_for(<span class="Identifier">@user</span>) <span class="rubyControl">do</span> |<span class="Identifier">form</span>| <span class="PreProc">%&gt;</span>
  <span class="Keyword">&lt;</span><span class="Conditional">p</span><span class="Keyword">&gt;</span>
    <span class="PreProc">&lt;%=</span> form.label(<span class="Constant">:name</span>, <span class="rubyStringDelimiter">'</span><span class="String">your name:</span><span class="rubyStringDelimiter">'</span>) <span class="PreProc">%&gt;</span>
    <span class="PreProc">&lt;%=</span> form.text_field(<span class="Constant">:name</span>) <span class="PreProc">%&gt;</span>
  <span class="Identifier">&lt;/</span><span class="Conditional">p</span><span class="Identifier">&gt;</span>
  <span class="Keyword">&lt;</span><span class="Conditional">p</span><span class="Keyword">&gt;</span>
    <span class="PreProc">&lt;%=</span> form.label(<span class="Constant">:password</span>, <span class="rubyStringDelimiter">'</span><span class="String">your password:</span><span class="rubyStringDelimiter">'</span>) <span class="PreProc">%&gt;</span>
    <span class="PreProc">&lt;%=</span> form.password_field(<span class="Constant">:password</span>) <span class="PreProc">%&gt;</span>
  <span class="Identifier">&lt;/</span><span class="Conditional">p</span><span class="Identifier">&gt;</span>
<span class="PreProc">&lt;%</span> <span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>You might think: &quot;That&#39;s rather neat!&quot; and it is! But it is still lacking a lot. For once it&#39;s not DRY. You can correct that by making your own form builder, moving stuff to partials and a lot of other great examples float around the web waiting to be implemented. But something strikes me here. If the form is an object, why aren&#39;t fields? Why don&#39;t we apply the same principle here? Fields can have a lot of properties that would make the block-with-object method a nice solution. A field may have label, but also a description, some javascript validation, it can be a required field. A field my have multiple fields in it, like multiple checkboxes or radiobuttons. A block-with-object method for your fields might look like this:</p>
<pre><span class="PreProc">&lt;%=</span> form.create_field(<span class="Constant">:name</span>) <span class="rubyControl">do</span> |<span class="Identifier">field</span>|
  field.type = <span class="Constant">:text_field</span>
  field.label = <span class="rubyStringDelimiter">'</span><span class="String">Name</span><span class="rubyStringDelimiter">'</span>
  field.required!
  field.description = <span class="rubyStringDelimiter">'</span><span class="String">Please enter your name here. It may only contain alphanumeric characters and underscores</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span> <span class="PreProc">%&gt;</span>

<span class="PreProc">&lt;%=</span> form.create_field(<span class="Constant">:category_ids</span>) <span class="rubyControl">do</span> |<span class="Identifier">field</span>|
  field.label = <span class="rubyStringDelimiter">'</span><span class="String">Select some categories</span><span class="rubyStringDelimiter">'</span>
  field.type = <span class="Constant">:checkboxes</span>
  field.add_options <span class="rubyControl">do</span> |<span class="Identifier">opt</span>|
    opt.add <span class="Number">1</span>, <span class="rubyStringDelimiter">'</span><span class="String">foo</span><span class="rubyStringDelimiter">'</span>
    opt.add <span class="Number">2</span>, <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>
  <span class="rubyControl">end</span>
<span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre>
<p>I hope you agree with me that this is much more readable and editable. It trades of long lines for more shorter lines which is a good trade-off. If you&#39;re using Haml for your views it&#39;s even more important to have short lines than in ERB. In Haml you can&#39;t easily break up lines so short lines of code is vital to the readability of your views. Views naturally have the tendency to become hard to follow and ugly, so it is recommended that important and complex parts of it (mainly views) stay easy and readable. Readability helps your maintainability. I am currently making this kind of form builder, so if you have any suggestions, please do!</p>

<p>But why stop here? Forms are not the only part which involves a lot of HTML and repetitive coding. Website often include blocks in a sidebar which are totally suited for this kind of solution. These are the days of glossy website designs, in the world of Web 2.0 every angle is softened or rounded. Sometimes this asks for a lot of HTML, building divs into divs. I&#39;m a fan of Haml for making this easy, but you need a way to shorten lines, and in some way &#39;metaprogram&#39; your HTML. At the risk of <a href="http://blog.thinkrelevance.com/2008/4/1/relevance-raises-3-6-million-from-spelvin-capital">sounding </a> &#39;<a href="http://blog.zenspider.com/2008/04/id-die-of-typing.html">Java-ish</a>&#39;, I&#39;d say it would be better to build an extra layer of abstraction into the so trusty MVC. In your view you decide what goes where, what your lines are and which fields are available. Above it lies an HTML layer which translates it to whatever your website is designed to look like. A view gets split in two: a structural layer and a design layer. If thought out well you can even change one layer without the need to change the other.</p>

<p>This might not be your solution. Your website might be too small to make such a difference. But it&#39;s worth thinking about it when you&#39;re building something. If you&#39;re making a helper-method, and you find yourself in need of a lot (say, more than 2) arguments, consider making a small object with some accessors to making this easy. Here is something to help you on your way:</p>
<pre># in your view, traditional way (which can get very long, depending on the number of arguments):
<span class="PreProc">&lt;%=</span> small_menu(<span class="Constant">:title</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">Monkey</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:foo</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>) <span class="PreProc">%&gt;</span>

# with a small helper class and a block structure it may become:
<span class="PreProc">&lt;%=</span> small_menu <span class="rubyControl">do</span> |<span class="Identifier">sm</span>|
  sm.title = <span class="rubyStringDelimiter">'</span><span class="String">Monkey</span><span class="rubyStringDelimiter">'</span>
  sm.foo = <span class="rubyStringDelimiter">'</span><span class="String">bar</span><span class="rubyStringDelimiter">'</span>
<span class="rubyControl">end</span> <span class="PreProc">%&gt;</span></pre><pre><span class="Comment"># you'll need this in your helper for that:</span>
<span class="Keyword">module</span> <span class="Type">SomeHelper</span>

  <span class="PreProc">def</span> <span class="Function">small_menu</span>
    sm = <span class="Type">SmallMenu</span>.new
    <span class="Keyword">yield</span> sm
    <span class="Comment"># construct your html here, using parameters from the sm-object</span>
  <span class="PreProc">end</span>

<span class="Keyword">end</span>

<span class="Comment"># in the same helper (only if it's short) or in another file (helper or lib)</span>
<span class="Keyword">class</span> <span class="Type">SmallMenu</span>
  <span class="Statement">attr_accessor</span> <span class="Constant">:title</span>, <span class="Constant">:link</span>, <span class="Constant">:partial</span>, <span class="Constant">:foo</span>
<span class="Keyword">end</span></pre>
<p>By the way, if you haven&#39;t seen it yet, you should watch <a href="http://railscasts.com/episodes/101">Railscast episode 101</a> for another nice way to incorporate classes into your helpers.</p>
]]>
      </description>
      <guid>http://iain.nl/bringing-objects-to-views</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Surrounding something with a div, conditionally.</title>
      <link>http://iain.nl/surrounding-something-with-a-div-conditionally</link>
      <pubDate>Thu, 20 Mar 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>A problem I keep running in to, especially with Haml, is how to render Ajax requests. Say you have
a partial on your page which is something dynamic, like a feedback form. Here you might want to
replace this partial with an updated version of that same partial. When making an ajax request,
you specify the id of the element you wish to update. But when the element is created inside the
partial, it gets rendered double.</p>
<pre><span class="Special">#</span><span class="Identifier">feedback</span>
  <span class="Special">=</span> remote_form_for(<span class="Identifier">@feedback</span> ||= <span class="Type">Feedback</span>.new, <span class="Constant">:url</span> =&gt; <span class="Identifier">@feedback</span>, <span class="Constant">:update</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">feedback</span><span class="rubyStringDelimiter">'</span>) <span class="rubyControl">do</span> |<span class="Identifier">f</span>|
    <span class="Special">=</span> f.input_field <span class="Constant">:message</span>
    <span class="Special">=</span> submit_tag</pre>
<p>will result after the button is pressed:</p>
<pre><span class="Keyword">&lt;</span><span class="Conditional">div</span><span class="Keyword"> </span><span class="Type">id</span><span class="Keyword">=</span><span class="String">"feedback"</span><span class="Keyword">&gt;</span>
  <span class="Keyword">&lt;</span><span class="Conditional">div</span><span class="Keyword"> </span><span class="Type">id</span><span class="Keyword">=</span><span class="String">"feedback"</span><span class="Keyword">&gt;</span>
    <span class="Keyword">&lt;</span><span class="Conditional">form</span><span class="Keyword">&gt;</span>etc
  <span class="Identifier">&lt;/</span><span class="Conditional">div</span><span class="Identifier">&gt;</span>
<span class="Identifier">&lt;/</span><span class="Conditional">div</span><span class="Identifier">&gt;</span></pre>
<p>One solution is to create the div outside of the partial, but that would make the partial less self
sufficient. Since I am a big fan of self sufficient partials, I&#39;d want to just render the partial,
and never to care about any div&#39;s around it.</p>

<p>An <strong>ugly</strong> solution, especially when using Haml, is to dynamically create the open and close tags:</p>
<pre><span class="Special">=</span> <span class="rubyStringDelimiter">'</span><span class="String">&lt;div id="feedback"&gt;</span><span class="rubyStringDelimiter">'</span> <span class="rubyControl">unless</span> request.xhr?
<span class="Special">-</span> remote_form_for(etc)
<span class="Special">=</span> <span class="rubyStringDelimiter">'</span><span class="String">&lt;/div&gt;</span><span class="rubyStringDelimiter">'</span> <span class="rubyControl">unless</span> request.xhr?</pre>
<p>My solution is a small helper, resulting in this view-code:</p>
<pre><span class="Special">=</span> content_for_ajax_request(<span class="Constant">:id</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">feedback</span><span class="rubyStringDelimiter">'</span>) <span class="rubyControl">do</span>
  <span class="Special">=</span> remote_form_for(etc)</pre>
<p>Which requires this helper:</p>
<pre><span class="PreProc">def</span> <span class="Function">content_for_ajax_request</span>(options = {}, &amp;block)
  c = capture_haml { <span class="Keyword">yield</span> }
  request.xhr? ? c : content_tag(<span class="Constant">:div</span>, c, options)
<span class="PreProc">end</span></pre>
<p>The only minor problem is, that it screws up the indentation, but I&#39;m not being picky this time.</p>

<p>When you&#39;re not using Haml, but ERB, just use this:</p>
<pre><span class="PreProc">def</span> <span class="Function">content_for_ajax_request</span>(options = {}, &amp;block)
  c = capture { <span class="Keyword">yield</span> }
  request.xhr? ? c : content_tag(<span class="Constant">:div</span>, c, options)
<span class="PreProc">end</span></pre>
<p>Naturally, you can change the condition, if you&#39;d like.</p>
<pre><span class="PreProc">def</span> <span class="Function">div_if</span>(condition, options = {}, &amp;block)
  c = capture { <span class="Keyword">yield</span> }
  condition ? c : content_tag(<span class="Constant">:div</span>, c, options)
<span class="PreProc">end</span></pre>
<p>This is exactly why I like Ruby so much. Using blocks can make your code so much sweeter...</p>
]]>
      </description>
      <guid>http://iain.nl/surrounding-something-with-a-div-conditionally</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Second Haml evaluation</title>
      <link>http://iain.nl/second-haml-evaluation</link>
      <pubDate>Mon, 10 Mar 2008 07:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>After using <a href="http://haml-lang.com/">Haml</a> for <a href="/first-haml-evaluation">over a month</a> now, I can now
really evaluate how Haml is to work with from day to day basis.</p>

<p>Haml actually is a blessing. Doing minor adjustments is very easy, your code remains looking nice,
the output keeps looking nice. Just be sure to know how to shift blocks of code to the left or right
in your favorite editor.</p>

<p>OK, there are some downsides. You have very little control over how you HTML turns out. It is
usually spot on, but sometimes you do have to use ERB. Making your own autocomplete boxes for
instance. Here I needed to use ERB, because the indentation would end up in the textfield, which
would break the functionality in IE6. You still have to use ERB in emails too, since you cannot
afford to go to a new line with every variable.</p>

<p>One thing that especially enjoys me is that you cannot go to the next line unpunished. Sometimes
you&#39;re tempted to enter a long line of Ruby code within your template. In ERB you could just go to
the next line and continue there. With Haml that&#39;s not the case. So rather than making long and ugly
lines of code, you should be triggered to use helpers more often. I need that nudge in the back.</p>

<p>But those are just tiny problems. After a while of using Haml, I can&#39;t imagine going back to ERB for
an entire website. It is too tiresome using ERB, compared to Haml. And a good programmer is a lazy
programmer, although admittedly not the other way round. ;)</p>

<p>One more tip: use helpers to render partials or partial-layouts to output HTML. That way you can
have this kind of code:</p>

<p>In your view:</p>
<pre><span class="Special">=</span> in_special_block <span class="rubyControl">do</span>
  <span class="Special">%</span><span class="Conditional">li</span><span class="Special">.</span><span class="Type">username</span><span class="Special">=</span>  h(<span class="Identifier">@user</span>.name)
  <span class="Special">%</span><span class="Conditional">li</span><span class="Special">.</span><span class="Type">edit_link</span><span class="Special">=</span> link_to( <span class="rubyStringDelimiter">'</span><span class="String">edit</span><span class="rubyStringDelimiter">'</span>, edit_user_url(<span class="Identifier">@user</span>) )</pre>
<p>And in your helper:</p>
<pre><span class="PreProc">def</span> <span class="Function">in_special_block</span>
  <span class="Comment"># do stuff</span>
  render(<span class="Constant">:layout</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">shared/block_layout</span><span class="rubyStringDelimiter">'</span>) { <span class="Keyword">yield</span> }
  <span class="Comment"># other stuff</span>
<span class="PreProc">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/second-haml-evaluation</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>First Haml evaluation</title>
      <link>http://iain.nl/first-haml-evaluation</link>
      <pubDate>Fri, 15 Feb 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>As I <a href="/the-knights-templater-part-ii-priory-of-haml">promised</a>, here is the evaluation of redoing a
site from ERB to <a href="http://haml-lang.com">Haml</a>. To immediately cut to the chase: Haml IS worth it!</p>

<ul>
<li>It&#39;s so definitely faster and easier to write than ERB.</li>
<li>Your HTML output is nicer.</li>
<li>Partials rendering with the right indentation automatically.</li>
<li>It forces you to take a good look of what you&#39;re actually making.</li>
<li>Because it&#39;s so strict on it&#39;s syntax, you will be using more helpers and custom model methods, which is a good thing.</li>
<li>No more forgetting to close a div and spending hours to find out which one.</li>
<li>Faster refactoring because of less code and easier to read.</li>
</ul>

<p>There are some downsides however. I&#39;d rather not talk about the hours I tried to fix some idiot
problem with partials and the locals option. Just use locals as less as possible, preferably not at
all. Some cons:</p>

<ul>
<li>Yet another syntax to be learned.</li>
<li>Errors with Haml syntax are a bit harder to locate, but you&#39;ll make less after you encountered a few.</li>
<li>A gem needs to be installed on the server, which can be difficult if you don&#39;t have root rights on the server</li>
<li>The syntax highlighter on VIm is not quite up to it.</li>
<li>Rails helpers screw up the nice HTML Haml creates for you. The form_tag helpers for example.</li>
</ul>

<p>So if you are starting a new project, or redoing the entire HTML of you&#39;re application: try Haml!
Chances are you&#39;ll like it!</p>
]]>
      </description>
      <guid>http://iain.nl/first-haml-evaluation</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>The Knights Templater part II: Priory of Haml</title>
      <link>http://iain.nl/the-knights-templater-part-ii-priory-of-haml</link>
      <pubDate>Fri, 01 Feb 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Of course it&#39;s no problem to upgrade from Ruby on Rails 1.2.6 to 2.0.2. Just make sure you don&#39;t fuck up your subversion when unfreezing the old and freezing the new version. I just wanted to have that out of the way, before starting this new adventure.</p>

<p>My current project (not being the same as the one from <a href="/the-agile-grail-and-the-knights-templater">my previous post about the knights templater</a>) in which I totally wrote **123 **views, of which **48 **partials. Since this project was so Agile, it would have made fucking of the ugly fat girl from some party look like it had been planned and completely documented months in advance, it has become a jungle of views rendering partials rendering partials rendering partials. The HTML had come from the templaters, the functionality is all finished. All we (<a href="http://ariekanarie.nl/">Arie </a>and me) need to do now is completely reimplement all the views. Yuck!</p>

<p><a href="http://haml-lang.com/">Haml</a> has been <a href="http://www.relevancellc.com/2008/1/10/help-graeme-make-his-case">popping</a> <a href="http://antoniocangiano.com/2008/01/08/ramaze-a-ruby-framework-that-will-amaze/">op</a> <a href="http://weblog.rubyonrails.com/2007/12/7/rails-2-0-it-s-done">often</a> <a href="http://weblog.rubyonrails.com/2007/7/10/haml-1-7">lately</a> <a href="http://agilewebdevelopment.com/plugins/haml">in</a> <a href="http://www.continuousthinking.com/2007/8/15/agile-conference-2007-day-two">my</a> feed reader. It certainly gets the community talking, but no-one really implements it just yet. I heard <a href="http://blog.obiefernandez.com/content/2008/01/are-you-using-h.html">Obie Fernandez</a>&#39;s new company <a href="http://www.hashrocket.com/">HashRocket</a> is using it. And since I&#39;m still an intern studying Ruby on Rails, this seemed the best moment to try it out for real.</p>

<p>But why Haml? Isn&#39;t there a faster way? A way to use the HTML done by the templaters?  Well, no not really. Because all templates are more ruby code than HTML anyway. It has more &quot;If I have one object of this, render that, or else, render that. If you have none of that, replace this with that and show this message&quot;. So much for separating Ruby code from HTML. In this project there is much more display logic than application logic and although I have about a dozen fully packed helpers, it can only go so far.</p>

<p>So we had to redo the site anyhow. It would be two weeks of sifting HTML from our old templates and replacing it with our new templates, putting in the ruby code again. Almost the same as retyping it all. So if I am going to be retyping it all, I want it to be fast. Let&#39;s put Haml to the test!</p>
]]>
      </description>
      <guid>http://iain.nl/the-knights-templater-part-ii-priory-of-haml</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Pluralize for GetText released</title>
      <link>http://iain.nl/pluralize-for-gettext-released</link>
      <pubDate>Sun, 20 Jan 2008 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I did some research into <a href="http://agilewebdevelopment.com/plugins/category/8">i18n plugins for Ruby on
Rails</a>. I found <a href="http://wiki.globalize-rails.org/">Globalize
</a>not manageable enough, especially looking at substitution of
values and pluralization. Click to globalize (http:&#47;&#47;www.lucaguidi.com&#47;pages&#47;click-to-globalize)
didn&#39;t support substitution or pluralization. Many (http:&#47;&#47;simple-localization.arkanis.de&#47;)
<a href="http://agilewebdevelopment.com/plugins/i18n">others</a> used symbols as translation key, but that
provided the same problem as Globalize.</p>

<p>So I turned to <a href="http://www.gnu.org/software/gettext/">Gettext</a>. Gettext uses .po- and .mo files,
like a proper GNU application, which attracted me. But when it came to substitution, small parts,
like link texts, were scattered through the language file. I had to come up with a little scheme.</p>

<p>So I wrote a simple plugin for Ruby on Rails. This plugin inspects a single string to get
pluralization with substitution. The single string keeps the translation in one place.</p>

<p>Although I created this plugin for gettext, it can be used whenever you like. If you&#39;re not using
gettext, <code>_(&quot;string&quot;).pluralize_for becomes &quot;string&quot;.pluralize_for</code>... Simple enough...</p>

<p>I&#39;ve opened a <a href="http://code.google.com/p/pluralize-for-gettext/">google-code spot</a>, so you can have a
peak there, although I haven&#39;t gotten round to filling out every page there.</p>

<p>Learn how to install gettext in <a href="http://manuals.rubyonrails.com/read/chapter/105">this excellent
guide</a>. Use this tip to get it <a href="http://zargony.com/2007/07/29/using-ruby-gettext-with-edge-rails/">working with Rails
2.0</a>.</p>

<h3 id="toc_0">Installation</h3>
<pre>./script/plugin <span class="Statement">install</span> <a href="http://pluralize-for-gettext.googlecode.com/svn/trunk/">http://pluralize-for-gettext.googlecode.com/svn/trunk/</a></pre>
<p>And then rename <code>vendor&#47;plugins&#47;svn</code> to <code>vendor&#47;plugins&#47;pluralize_for_gettext</code></p>

<h3 id="toc_1">Examples</h3>
<pre><span class="PreProc">&lt;%=</span>_(<span class="rubyStringDelimiter">'</span><span class="String">No posts ~~ Only one post ~~ You have {$N} posts!</span><span class="rubyStringDelimiter">'</span>).pluralize_for(<span class="Type">Post</span>.count) <span class="PreProc">%&gt;</span></pre>
<p>The example speaks for itself.</p>

<p>You can change the conditions for each part in the string:</p>
<pre><span class="PreProc">&lt;%=</span>_(<span class="rubyStringDelimiter">'</span><span class="String">~~$N==0: No posts ~~$N==1: Only one post ~~else: You have {$N} posts</span><span class="rubyStringDelimiter">'</span>).pluralize_for(<span class="Type">Post</span>.count)<span class="PreProc">%&gt;</span></pre>
<p>Note: The translator can change the logic for this, for languages with weird pluralization rules. ;)</p>

<p>Caution: It&#39;s being eval&#39;ed, so always check language files (or ruby code) for any Ruby injections.</p>

<h3 id="toc_2">Substituting more variables</h3>

<p>Why not use the default sprintf-like function from rails? You&#39;d get this:</p>
<pre><span class="PreProc">&lt;%</span>_(<span class="rubyStringDelimiter">'</span><span class="String">You have %d posts, view %s</span><span class="rubyStringDelimiter">'</span>) % [ <span class="Type">Post</span>.count, link_to(_(<span class="rubyStringDelimiter">'</span><span class="String">more</span><span class="rubyStringDelimiter">'</span>), view_more_url)<span class="PreProc">%&gt;</span></pre>
<p>You&#39;d get multiple entries in you .po file, and just &#39;more&#39; can&#39;t be translated differently
according to the context. The point of this whole exercise was to keep text that appears in one
place together in the .po-file.</p>

<p>More advanced, for entering links and stuff, simply use {1:your text} and pass a block to the
function to manipulate the texts in anyway you like. The number becomes the id for the array, so be
careful in how you use them.</p>
<pre><span class="PreProc">&lt;%=</span>_(<span class="rubyStringDelimiter">'</span><span class="String">No posts, create one by clicking {1:here} ~~ Only one post ~~ You have {$N} posts ~~$N&amp;gt;6: You have {$N} posts, view {2:more}</span><span class="rubyStringDelimiter">'</span>).pluralize_for(<span class="Type">Post</span>.count) <span class="rubyControl">do</span> |<span class="Identifier">i</span>|
    i[<span class="Number">1</span>] = link_to(i[<span class="Number">1</span>], create_post_url) <span class="rubyControl">if</span> i[<span class="Number">1</span>]
    i[<span class="Number">2</span>] = link_to(i[<span class="Number">2</span>], view_more_url) <span class="rubyControl">if</span> i[<span class="Number">2</span>]
  <span class="PreProc">%&gt;</span></pre>
<p>Which would result in the .po file:</p>
<pre><span class="PreProc">#: app/controllers/some_controller.rb:102</span>
  msgid <span class="Comment">"No posts, create one by clicking {1:here} ~~ Only one post ~~ You have {$N} posts ~$N&gt;6~ You have {$N} posts, view {2:more}"</span>
  msgstr <span class="Comment">"Geen artikelen, {1:plaats een artikel} ~~ Slechts een artikel ~~ Je hebt {$N} artikelen ~$N&gt;6~ Je hebt {$N} artikelen ({2:bekijk meer...})"</span></pre>
<h3 id="toc_3">Simple pluralizations</h3>

<p>Perhaps you just want to specify a singular and plural for one word in the entire sentence:</p>
<pre><span class="PreProc">&lt;%=</span>_(<span class="rubyStringDelimiter">'</span><span class="String">You have {$N} {post|posts}</span><span class="rubyStringDelimiter">'</span>).pluralize_for(<span class="Type">Post</span>.count)<span class="PreProc">%&gt;</span></pre>
<p>English is simpler than many other languages, so the translator could change it into the more
elaborate version:</p>
<pre><span class="PreProc">#: app/controllers/some_controller.rb:102</span>
  msgid <span class="Comment">"You have {$N} {post|posts}"</span>
  msgstr <span class="Comment">"~~$N==0: Helemaal geen artikelen ~~$N==1: U heeft een artikel ~~$N&gt;1: U heeft {$N} artikelen"</span><span class="Identifier">&lt;/pre&gt;</span></pre>
<h1048576 id="toc_3151568">Nesting</h3>

<p>You can nest any way you&#39;d like, but keep it sane. Here&#39;s a nice example:</p>
<pre><span class="rubyStringDelimiter">"</span><span class="String">$N==0:No posts. {1:create one}.~~else:You have {1:{$N} new {post|posts}}...</span><span class="rubyStringDelimiter">"</span>.pluralize_for(<span class="Type">Post</span>.count) <span class="rubyControl">do</span> |<span class="Identifier">i</span>|
  i[<span class="Number">1</span>] =  link_to(i[<span class="Number">1</span>], url) <span class="Conditional">if</span> i[<span class="Number">1</span>]
  i[<span class="Number">2</span>] = link_to(i[<span class="Number">2</span>], other_url) <span class="Conditional">if</span> i[<span class="Number">2</span>]
<span class="rubyControl">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/pluralize-for-gettext-released</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Plain Text Stories and Vim</title>
      <link>http://iain.nl/plain-text-stories-and-vim</link>
      <pubDate>Tue, 18 Dec 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p><strong>Update:</strong> Updated the syntax file, redownload it if you got it before December 19th 2007.</p>

<p>More news about my adventures with Selenium. It&#39;s hot and juicy, so lot&#39;s of exciting new things to
do. I made a syntax highlighter for plain text stories in vim. Here&#39;s how it looks:</p>

<p>To make it look like this, I adjusted the slate colorscheme and added my own story syntax file.</p>

<h3 id="toc_0">Here is what you need to do:</h3>

<p>Put the black-slate colorscheme file in &#47;usr&#47;share&#47;vim&#47;vim71&#47;colors directory</p>

<p>Put the story syntax file in &#47;usr&#47;share&#47;vim&#47;vim71&#47;syntax directory</p>

<p>Append these lines to the end of &#47;usr&#47;share&#47;vim&#47;vim71&#47;scripts.vim:</p>
<pre><span class="Statement">if</span> <span class="Function">did_filetype</span><span class="Delimiter">()</span>
  <span class="Statement">finish</span>
<span class="Statement">endif</span>
<span class="Statement">if</span> <span class="Function">getline</span><span class="Delimiter">(</span><span class="Number">1</span><span class="Delimiter">)</span> <span class="Operator">=~</span> <span class="String">"^Story:\s.*"</span>
  <span class="Statement">setf</span> story
<span class="Statement">endif</span></pre>
<p>Add these lines to your personal vimrc (~&#47;.vimrc) or the systemwide vimrc file (&#47;etc&#47;vim&#47;vimrc):</p>
<pre><span class="Statement">set</span> <span class="PreProc">background</span>=dark
<span class="Statement">set</span> <span class="PreProc">tabstop</span>=2   <span class="Comment">"please default all tabs to 2 spaces</span>
<span class="Statement">set</span> <span class="PreProc">shiftwidth</span>=2
<span class="Statement">set</span> <span class="PreProc">expandtab</span>
<span class="Statement">set</span> <span class="PreProc">number</span>
<span class="Statement">set</span> <span class="PreProc">smartindent</span>
<span class="Statement">set</span> <span class="PreProc">smarttab</span>
<span class="Statement">filetype</span> <span class="Type">plugin</span> <span class="Type">on</span>
<span class="Statement">filetype</span> <span class="Type">indent</span> <span class="Type">on</span>
<span class="Statement">colorscheme</span> black<span class="Operator">-</span>slate</pre>
<p>Type your plain text stories, make sure every story file starts with &#39;Story:&#39; It won&#39;t recognize
it&#39;s a plain text story right away, so first type &#39;Story:&#39;, save it and reopen it to get nice
colours.</p>

<p>By the way, Arie has made a syntax highlighter for the google javascript syntax highlighter. Keep a
look out on <a href="http://ariekanarie.nl/">his blog</a> too!</p>
]]>
      </description>
      <guid>http://iain.nl/plain-text-stories-and-vim</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Selenium clicking a label</title>
      <link>http://iain.nl/selenium-clicking-a-label</link>
      <pubDate>Tue, 18 Dec 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I am making some acceptance tests for the LevenAls website, using plain text stories from <a href="http://blog.davidchelimsky.net/articles/2007/10/25/plain-text-stories-part-iii">David
Chelimsky</a>
together with the Selenium runner from <a href="http://www.kerrybuckley.com/2007/11/07/driving-selenium-from-the-rspec-story-runner-rbehave%0A/">Kerry
Buckley</a></p>
<pre>Story: Selenium clicking a label

As a developer
I wanted to make acceptence tests
So I installed Cucumber and Selenium

  <span class="PreProc">Scenario:</span> Writing clean tests
    <span class="Function">When</span> I wanted to make the stories as clean as possible
    <span class="Function">And</span> I wanted to click a rails generated radiobutton
    <span class="Type">Then</span> the story became ugly
    <span class="Type">And</span> it had lines like 'the user clicks a customer_gender_m button'

  <span class="PreProc">Scenario:</span> I made a step for labels, getting the text
    <span class="Function">When</span> I wanted to get rid of it
    <span class="Function">And</span> I couldn't find an easy answer
    <span class="Function">And</span> I spent the better part of my evening googling it
    <span class="Type">Then</span> I made a post on the Selenium forum
    <span class="Type">And</span> asked for advice

  <span class="PreProc">Scenario:</span> I found a solution myself
    <span class="Function">When</span> I was sitting in the train
    <span class="Function">And</span> I was trying all kinds of solutions
    <span class="Type">Then</span> I stumbled upon the solution
    <span class="Type">And</span> I was overjoyed
    <span class="Type">And</span> it was: $selenium.click("//label[text()='#{label}']")</pre>
<p>So here is the entire step:</p>
<pre><span class="Type">When</span> <span class="rubyStringDelimiter">"</span><span class="String">the user clicks on a $element labelled $label</span><span class="rubyStringDelimiter">"</span> <span class="rubyControl">do</span> |<span class="Identifier">element</span>, <span class="Identifier">label</span>|
  <span class="Identifier">$selenium</span>.click <span class="rubyStringDelimiter">"</span><span class="String">//label[text()='</span><span class="rubyInterpolationDelimiter">#{</span>label<span class="rubyInterpolationDelimiter">}</span><span class="String">']</span><span class="rubyStringDelimiter">"</span>
<span class="rubyControl">end</span></pre>]]>
      </description>
      <guid>http://iain.nl/selenium-clicking-a-label</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>The Agile Grail and the Knights Templater</title>
      <link>http://iain.nl/the-agile-grail-and-the-knights-templater</link>
      <pubDate>Fri, 14 Dec 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I&#39;ve been working on a very rapid implemented website with Rails this week. It has been an exiting week. It all started on a Monday, when I overslept, and my colleague (<a href="http://ariekanarie.nl">Arie</a>) smiled at me and said: &quot;You&#39;ll be working with me this week&quot;. I liked the idea. Since we started working there we both worked on our own Rails projects, but never together. He continued: &quot;You know the <em>Leven Als</em> website? It&#39;s deadline has been changed... to this week, preferably to yesterday!&quot; That certainly was a challenge. I knew that the functional and graphical designers had been working on it for quite some time, but I&#39;ve never heard of it ever coming to the implementation phase. Three quarters of the HTML were done and we had 4 days to start a Ruby project from scratch and make it.</p>

<p>Luckily we were assured by the project manager: &quot;This is an easy website. People enter the website, choose which prize they want to win, enter some data and that&#39;s it. Nothing big, because there are no users having to log in.&quot; After drawing up a rudimentary class diagram I found out that a website without users is in fact quite hard! You can invite more than one person to the company (a big Dutch insurance company), you have to insure that all it&#39;s invites becomes linked to the same person for letting him have more chance of winning the prize. We had to fake logged in users and all relations that user had, put it all into a session, but still use the database on every form to utilize the validation ActiveRecord gives us.</p>

<p>Speaking of testing, we&#39;re quite fans of Behavior Driven Development, using Rspec and user stories and such, but we had no time for it. We are going to write some specs and acceptance tests next week, after the website goes live, hopefully finding no big bugs after that. With a few managers looking down on our shoulders every few hours, the pressure was on to come up with as much functionality in a short amount of time.  Thus making the <a href="http://www.dilbert.com/comics/dilbert/archive/images/dilbert2666700071126.gif">Dilbert way of Agile development</a> a reality.</p>

<p>Still there was a black hole of productivity lurking. What would cost us the most time, was implementing the HTML. For years, any decent IT company has it&#39;s own designing team with HTML template makers and all. These people know a lot about all the quirks of this horribly abused markup language, and spit out giant blobs of static pages representing each page of the application. And although it looks pretty, for a developer in Rails, it&#39;s a nightmare of converting that into Rails views, templates and partials. Every image tag, label, form element and so on needed to be looked at, replaced or altered. With no consideration of how difficult javascript can be, dropdowns magically interacting with the page are added. A button, described with &quot;doing the obvious thing&quot;, would have to do all kinds of fancy Ajax stuff, being as nice as your everyday Google-application. Designers never think about error messages, where they should go and how your application should deal with unexpected behaviour.  By far the worst thing is that you&#39;ll be given the entire CSS every time, so you had to dig through it to find changes, convert it again and implement it.</p>

<p>But, despite of it all, I like the outcome. Everyone did their best, everyone with a bit of HTML knowledge stepped in to help, to make the deadline. It was definitely worth it!</p>

<p><strong>Update:</strong> Leven is now live on <a href="http://www.levenals.nl/">http:&#47;&#47;www.levenals.nl&#47;</a></p>

<p>Here are some stats:</p>
<pre>+----------------------+-------+-------+---------+---------+-----+-------+
| Name                 | Lines |   LOC | Classes | Methods | M/C | LOC/M |
+----------------------+-------+-------+---------+---------+-----+-------+
| Controllers          |   244 |   204 |       4 |      20 |   5 |     8 |
| Helpers              |    19 |    16 |       0 |       1 |   0 |    14 |
| Models               |   215 |   167 |       7 |      20 |   2 |     6 |
| Libraries            |     0 |     0 |       0 |       0 |   0 |     0 |
| Integration tests    |     0 |     0 |       0 |       0 |   0 |     0 |
| Functional tests     |    24 |    18 |       3 |       3 |   1 |     4 |
| Unit tests           |    61 |    46 |       7 |       7 |   1 |     4 |
+----------------------+-------+-------+---------+---------+-----+-------+
| Total                |   563 |   451 |      21 |      51 |   2 |     6 |
+----------------------+-------+-------+---------+---------+-----+-------+
  Code LOC: 387     Test LOC: 64     Code to Test Ratio: 1:0.2
</pre>]]>
      </description>
      <guid>http://iain.nl/the-agile-grail-and-the-knights-templater</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Rcov all the way</title>
      <link>http://iain.nl/rcov-all-the-way</link>
      <pubDate>Mon, 10 Dec 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I installed the rails_rcov plugin to see the coverage like any good programmer ;-) But when I want
to know what all the tests combined produce in coverage, it just produced the coverage reports of
each individual test (units, functionals and integration) and replacing each with one another. I am
not a briliant googler, and when I couldn&#39;t find the answer in time, I decided to make my own rake
task for it. Here it is:</p>
<pre>namespace <span class="Constant">:test</span> <span class="rubyControl">do</span>
  desc <span class="rubyStringDelimiter">"</span><span class="String">Run all tests at once through rcov.</span><span class="rubyStringDelimiter">"</span>
  task <span class="Constant">:rcov</span> <span class="rubyControl">do</span>
    test_files = <span class="Type">FileList</span>[<span class="rubyStringDelimiter">'</span><span class="String">test/**/*_test.rb</span><span class="rubyStringDelimiter">'</span>]
    output_dir = <span class="Type">File</span>.expand_path(<span class="rubyStringDelimiter">"</span><span class="String">./coverage/all/</span><span class="rubyStringDelimiter">"</span>)
    command = <span class="rubyStringDelimiter">"</span><span class="String">rcov -o \"</span><span class="rubyInterpolationDelimiter">#{</span>output_dir<span class="rubyInterpolationDelimiter">}</span><span class="String">\" --rails --sort=coverage -T -x \"gems/*,rcov*,lib/*\" \"</span><span class="rubyInterpolationDelimiter">#{</span>test_files.join(<span class="rubyStringDelimiter">'</span><span class="String">" "</span><span class="rubyStringDelimiter">'</span>)<span class="rubyInterpolationDelimiter">}</span><span class="String">\"</span><span class="rubyStringDelimiter">"</span>
    puts command
    puts <span class="rubyStringDelimiter">`</span><span class="rubyInterpolationDelimiter">#{</span>command<span class="rubyInterpolationDelimiter">}</span><span class="rubyStringDelimiter">`</span>
    puts <span class="rubyStringDelimiter">"</span><span class="String">View all results at &lt;file://</span><span class="rubyInterpolationDelimiter">#{</span>output_dir<span class="rubyInterpolationDelimiter">}</span><span class="String">/index.html&gt;</span><span class="rubyStringDelimiter">"</span>
  <span class="rubyControl">end</span>
<span class="rubyControl">end</span></pre>
<p>Now, it doesn&#39;t take any argument yet, but it works quite all right.</p>
]]>
      </description>
      <guid>http://iain.nl/rcov-all-the-way</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Many to Many Relationships with Extra Data, Part I</title>
      <link>http://iain.nl/many-to-many-relationships-with-extra-data-part-i</link>
      <pubDate>Wed, 28 Nov 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Everybody probably read about has_many :through relations. With one simple command you can do some
amazing stuff. Consider the following:</p>
<pre><span class="Keyword">class</span> <span class="Type">User</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  has_many <span class="Constant">:subscriptions</span>
  has_many <span class="Constant">:newsletters</span>, <span class="Constant">:through</span> =&gt; <span class="Constant">:subscriptions</span>
<span class="Keyword">end</span>

<span class="Keyword">class</span> <span class="Type">Subscription</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  belongs_to <span class="Constant">:user</span>, <span class="Constant">:dependent</span> =&gt; <span class="Constant">:destroy</span>
  belongs_to <span class="Constant">:newsletter</span>, <span class="Constant">:dependent</span> =&gt; <span class="Constant">:destroy</span>
<span class="Keyword">end</span>

<span class="Keyword">class</span> <span class="Type">Newsletter</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>
  has_many <span class="Constant">:subscriptions</span>
  has_many <span class="Constant">:users</span>, <span class="Constant">:through</span> =&gt; <span class="Constant">:subscriptions</span>
  has_many <span class="Constant">:old_users</span>, <span class="Constant">:through</span> =&gt; <span class="Constant">:subscription</span>, <span class="Constant">:conditions</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">age &gt; 60</span><span class="rubyStringDelimiter">'</span>
<span class="Keyword">end</span></pre>
<p>Now you&#39;ll see that having a nice name for the join model is important for keeping it readable. From
personal experience I really need to repeat that: <strong>It is important to give a good name to your join
model.</strong> You might be tempted to use the default way of calling has_and_belongs_to_many. That would
be newsletter_users. It would be incredibly annoying to have to refer to that name all the time,
confusing and ugly.</p>

<p>Anyway, with this in place you can do nice stuff like: <code>current_user.newsletters</code> or
<code>@my_mag.old_users</code>. It&#39;s cool, but still very elementary. And though you can do much more than
this, there are still some loose ends. Sometimes you&#39;ll want to have the subscription, because
you&#39;ll want to update it, or destroy it, or whatever. Here is one of many solutions:</p>
<pre><span class="Keyword">class</span> <span class="Type">Newsletter</span> &lt; <span class="Type">ActiveRecord</span>::<span class="Type">Base</span>

  <span class="Comment"># amongst all the other stuff</span>

  <span class="Comment"># find the subscription, call it like this:</span>
  <span class="Comment">#   @newsletter.subscription_by(current_user).created_at</span>
  <span class="PreProc">def</span> <span class="Function">subscription_by</span>(user)
    <span class="Constant">self</span>.subscriptions.find_by_user_id(user.id)
  <span class="PreProc">end</span>

  <span class="Comment"># Creates a new subscription or updates the one already there, with the given attributes</span>
  <span class="PreProc">def</span> <span class="Function">save_subscription_for</span>(user, attributes = {})
    s = <span class="Constant">self</span>.subscription_by(user) || <span class="Constant">self</span>.subscriptions.new(<span class="Constant">:user</span> =&gt; user)
    s.update_attributes(attributes)
  <span class="PreProc">end</span>

<span class="Keyword">end</span></pre>
<p>There is more and more elegant ways to do this. I&#39;ll get back to you on that. Leave any suggestions
in the comments.</p>
]]>
      </description>
      <guid>http://iain.nl/many-to-many-relationships-with-extra-data-part-i</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Fancy Named Routes - Part II</title>
      <link>http://iain.nl/fancy-named-routes-part-ii</link>
      <pubDate>Wed, 21 Nov 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>Here are some improvements for <a href="/fancy-named-routes">Fancy Named Routes - Part I</a>. In this part we
will be adding a more thorough solution for the html escaping in everywhere. I noticed this was
absolutely important, when I tried to view an escaped url in a production environment with Apache
with mod_proxy and mongrel_cluster. Apache doesn&#39;t like &#39;%2F&#39; in the title, and doesn&#39;t forward the
request to mongrel, so it returns a nice 404.</p>

<p>To rid yourself of the problem once and for all, add this to your ApplicationController:</p>
<pre><span class="PreProc">def</span> <span class="Function">url_for</span>(options)
  url = <span class="Keyword">super</span>(options)
  url.gsub!(<span class="rubyStringDelimiter">"</span><span class="String">%2F</span><span class="rubyStringDelimiter">"</span>,<span class="rubyStringDelimiter">"</span><span class="String">/</span><span class="rubyStringDelimiter">"</span>) <span class="Conditional">if</span> has_nice_url?(url)
  url
<span class="PreProc">end</span>

<span class="PreProc">def</span> <span class="Function">has_nice_url?</span>(link)
  rs = ::<span class="Type">ActionController</span>::<span class="Type">Routing</span>::<span class="Type">Routes</span>
  segments = rs.recognize_path link
  rs.named_routes.routes.each <span class="rubyControl">do</span> |<span class="Identifier">key</span>,<span class="Identifier">value</span>|
    <span class="rubyControl">return</span> <span class="Constant">true</span> <span class="Conditional">if</span>
      value.defaults.has_value?(segments[<span class="Constant">:controller</span>]) <span class="rubyControl">and</span>
      value.defaults.has_value?(segments[<span class="Constant">:action</span>]) <span class="rubyControl">and</span>
      value.defaults.include?(<span class="Constant">:nice_url</span>)
  <span class="rubyControl">end</span>
<span class="PreProc">rescue</span> ::<span class="Type">ActionController</span>::<span class="Type">RoutingError</span>
  logger.debug{<span class="rubyStringDelimiter">"</span><span class="String">RoutingError has occured</span><span class="rubyStringDelimiter">"</span>}
<span class="PreProc">end</span></pre>
<p>Now there is no need for overloading link_to or redirected_to. Remember, you&#39;ll need this in your
config&#47;routes.rb, to make it all work:</p>
<pre>map.show_article <span class="rubyStringDelimiter">'</span><span class="String">article/:id/*nice_url</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">articles</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:action</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">show</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:nice_url</span> =&gt; <span class="Constant">nil</span></pre>
<p>And in your model, you have to add:</p>
<pre><span class="PreProc">def</span> <span class="Function">to_param</span>
  <span class="Constant">self</span>.id.to_s+<span class="rubyStringDelimiter">'</span><span class="String">/</span><span class="rubyStringDelimiter">'</span>+<span class="Constant">self</span>.title.gsub(<span class="rubyRegexpDelimiter">/</span><span class="Special">\W</span><span class="Special">+</span><span class="rubyRegexpDelimiter">/</span>,<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).downcase+<span class="rubyStringDelimiter">'</span><span class="String">.html</span><span class="rubyStringDelimiter">'</span>
<span class="PreProc">end</span></pre>
<p>Now you can make awesome links like this:</p>
<pre>link_to h(<span class="Identifier">@article</span>.title), show_article_url(<span class="Identifier">@article</span>)
redirect_to show_article_url(<span class="Identifier">@article</span>)</pre>]]>
      </description>
      <guid>http://iain.nl/fancy-named-routes-part-ii</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
    <item>
      <title>Fancy Named Routes - Part I</title>
      <link>http://iain.nl/fancy-named-routes</link>
      <pubDate>Thu, 15 Nov 2007 08:00:00 GMT</pubDate>
      <description>
        <![CDATA[<p>I know <a href="http://tweakers.net">tweakers.net</a> has it, I liked it,
and I wanted it for myself. The uris of news items are like this:
<code>http:&#47;&#47;core.tweakers.net&#47;nieuws&#47;50373&#47;intel-stoot-ontwikkeling-netwerkprocessors-af.html</code></p>

<p>First you get the id, than you get a nice version of the title ending with .html. This is a nice way
of making links, scoring high for a googlebot and is incredibly easy to read.</p>

<p>I first tried to use only the title as an identifier. Now normally there would be a problem with
having titles in your uri. First of all you might want to have special characters in your title.
Rails automatically converts them back into the characters they are when evaluating the routes, so
it would result in this problem: <code>&#47;news&#47;my%2Ftitle.html</code> would evaluate to <code>&#47;news&#47;my&#47;title.html</code>,
which the Rails Router doesn&#39;t understand.</p>

<p>Besides, it doesn&#39;t look good. But when changing the title to <code>my-title.html</code>, just for output,
there is no good way of getting it back to the original title. Even more problematic is <code>my&#47;title</code>
and <code>my-title</code> would lead to the same page. I concluded that you&#39;ll definitely need an id in your
uri. But how would I have the title in it then?</p>

<p>The solution is a nice named route, like this one:</p>
<pre>map.news <span class="rubyStringDelimiter">'</span><span class="String">news/:id/*nice_url</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">news</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:action</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">show</span><span class="rubyStringDelimiter">'</span></pre>
<p>Now to get the title to appear automatically, so you don&#39;t have to code it every time you make a
link. Go to the model and add this method:</p>
<pre><span class="PreProc">def</span> <span class="Function">to_param</span>
  <span class="Constant">self</span>.id.to_s+<span class="rubyStringDelimiter">'</span><span class="String">/</span><span class="rubyStringDelimiter">'</span>+<span class="Constant">self</span>.title.gsub(<span class="rubyRegexpDelimiter">/</span><span class="Special">\W</span><span class="rubyRegexpDelimiter">/</span>, <span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).squeeze(<span class="rubyStringDelimiter">'</span><span class="String">-</span><span class="rubyStringDelimiter">'</span>).downcase+<span class="rubyStringDelimiter">'</span><span class="String">.html</span><span class="rubyStringDelimiter">'</span>
<span class="PreProc">end</span></pre>
<p>Now every time you use <code>news_url(@news)</code> it adds the title nicely formatted. One downside though:
Because it is a parameter Ruby converts it to <code>%2F</code>. As it should, I might add. But in this case we
don&#39;t want it, it looks silly. But it works. Fixing this is a bit tricky. You must overload the
<code>link_to</code> function. I&#39;ve done it like this:</p>
<pre><span class="PreProc">def</span> <span class="Function">link_to</span>(text, link, *options)
  <span class="Keyword">super</span>(text, convert_nice_url(link), *options)
<span class="PreProc">end</span>

<span class="Statement">private</span>

  <span class="PreProc">def</span> <span class="Function">bare_path</span>(txt)
    txt.sub(<span class="rubyRegexpDelimiter">/</span><span class="Special">^</span><span class="Special">\/</span><span class="Special">*</span><span class="rubyRegexpDelimiter">/</span>, <span class="rubyStringDelimiter">'</span><span class="String">/</span><span class="rubyStringDelimiter">'</span>).sub(index_url,<span class="rubyStringDelimiter">''</span>)
  <span class="PreProc">end</span>

  <span class="PreProc">def</span> <span class="Function">convert_nice_url</span>(link)
    link = url_for(link) <span class="Conditional">unless</span> link.is_a?(<span class="Type">String</span>)
    rs = ::<span class="Type">ActionController</span>::<span class="Type">Routing</span>::<span class="Type">Routes</span>
    segments = rs.recognize_path(bare_path(link))
    has_nice_url = <span class="Constant">false</span>
    rs.named_routes.routes.each <span class="rubyControl">do</span> |<span class="Identifier">key</span>,<span class="Identifier">value</span>|
      has_nice_url = <span class="Constant">true</span> <span class="Conditional">if</span>
        value.defaults.has_value?(segments[<span class="Constant">:controller</span>]) <span class="rubyControl">and</span>
        value.defaults.has_value?(segments[<span class="Constant">:action</span>]) <span class="rubyControl">and</span>
        value.defaults.include?(<span class="Constant">:nice_url</span>)
    <span class="rubyControl">end</span>
    link.gsub!(<span class="rubyStringDelimiter">"</span><span class="String">%2F</span><span class="rubyStringDelimiter">"</span>,<span class="rubyStringDelimiter">"</span><span class="String">/</span><span class="rubyStringDelimiter">"</span>) <span class="Conditional">if</span> has_nice_url
    <span class="rubyControl">return</span> link
  <span class="PreProc">rescue</span> ::<span class="Type">ActionController</span>::<span class="Type">RoutingError</span>
    <span class="rubyControl">return</span> link
  <span class="PreProc">end</span></pre>
<p>It looks if your route has the parameter <code>nice_url</code> and in that case it replaces <code>%2F</code> with genuine
forward slashes. You might want to do this for <code>link_to_remote</code> and <code>redirect_to</code> as well.</p>

<p><strong>Update:</strong> In <code>routes.rb</code>, don&#39;t forget to add a named route called index, pointing to <code>&#39;&#39;</code>, as a
default route. This script needs that. Furthermore, you need to make the default of the parameter
<code>nice_url</code> nil. This is the final version of routes.rb:</p>
<pre>map.index <span class="rubyStringDelimiter">''</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">news</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:action</span>=&gt;<span class="rubyStringDelimiter">'</span><span class="String">index</span><span class="rubyStringDelimiter">'</span>
map.news <span class="rubyStringDelimiter">'</span><span class="String">news/:id/*nice_url</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:controller</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">news</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:action</span> =&gt; <span class="rubyStringDelimiter">'</span><span class="String">show</span><span class="rubyStringDelimiter">'</span>, <span class="Constant">:nice_url</span> =&gt; <span class="Constant">nil</span></pre>
<p><strong>Update 2:</strong> I will be following up on this item, to properly implement this. Come back again later!</p>
]]>
      </description>
      <guid>http://iain.nl/fancy-named-routes</guid>
      <author>iain@iain.nl (iain hecker)</author>
    </item>
  </channel>
</rss>
